Laravel 4 Eloquent ORM通过动态属性访问一对一关系

时间:2013-06-02 22:46:33

标签: laravel laravel-4 eloquent

我试图在'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打印出用户模型字段就好了,但没有显示任何关系的痕迹; $ 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;

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

有什么建议吗?

1 个答案:

答案 0 :(得分:7)

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

这意味着我必须将我的模型类和文件名命名为UserProfile(即使我的MySql表名为“user_profiles”),然后将我的User模型更新为具有名为userProfile()的函数。

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

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