【问题标题】:Laravel 4 Eloquent ORM accessing one-to-one relationship through dynamic propertiesLaravel 4 Eloquent ORM 通过动态属性访问一对一关系
【发布时间】:2013-06-02 22:46:33
【问题描述】:

我试图在“Users”表和“User_profiles”表之间建立一个非常简单的关系模型。每个用户都有一个 user_profile,所以它是一个简单的一对一。根据@http://four.laravel.com/docs/eloquent#one-to-one 找到的文档,我已将以下功能添加到我的用户模型中:

public function user_profile()
{
    return $this->hasOne('User_profile');
}

这是在我的 User_profile 模型中定义的关系:

public function user()
{
    return $this->belongsTo('User');
}

我正在尝试像这样从控制器访问:

    // Get current user
    $user = User::find(Auth::user()->id);
    $profile = $user->user_profile;

    print_r($user);
    print_r($profile);

    echo "User's name is: " . $user->user_profile->first_name . ' ' . $user->user_profile->last_name;

不幸的是,打印 $user 可以很好地打印出 User 模型字段,但没有显示任何关系痕迹; $profile 为空。 'relations' 数组也是空的,我猜应该可以填充。

我正在尝试使用此处建议的“动态属性”http://four.laravel.com/docs/eloquent#dynamic-properties

否则我就去:

echo "User's name is: " . $user->user_profile()->first()->first_name . ' ' . $user->user_profile()->first()->last_name;

它有效..但我真的不喜欢这样做。

有什么建议吗?

【问题讨论】:

    标签: laravel laravel-4 eloquent


    【解决方案1】:

    好的,所以问题与在类名中使用下划线有关。 Laravel 遵循 here 概述的 PSR 0 和 1。

    这意味着我必须将我的模型类和文件名命名为 UserProfile(即使我的 MySql 表名仍然是“user_profiles”),然后更新我的用户模型以拥有一个名为 userProfile() 的函数。

    更新命名后,我可以通过执行以下操作自动访问关系:

    $user = Auth::user();
    echo $user->userProfile->first_name;
    

    【讨论】:

    • 我喜欢 L4,但这个方面必须吸引很多人。我遇到了类似的问题,但在我的情况下,它与产品类型有关,结果我必须将关系方法命名为 productType() 而不是 producttype()。感谢您的发布,希望它可以帮助其他一些人。
    • 是的,此外,重命名对象(例如表及其相关表)很烦人,但您最终会回到表字段本身的下划线命名,即 first_name。这种不一致有点令人恼火。
    猜你喜欢
    • 2018-12-29
    • 1970-01-01
    • 2015-11-22
    • 1970-01-01
    • 2015-04-04
    • 1970-01-01
    • 2016-02-11
    • 1970-01-01
    • 2023-03-17
    相关资源
    最近更新 更多