gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 18:32:52 25 4
gpt4 key购买 nike

我正在尝试在“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');
}

我正在尝试像这样从 Controller 访问:

    // 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 可以很好地打印出用户模型字段,但没有显示任何关系的痕迹; $配置文件为空。 “关系”数组也是空的,我猜它可能应该被填充。

我正在尝试使用此处建议的“动态属性”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 遵循 PSR 0 和 1,如 here 所述.

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

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

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

关于Laravel 4 Eloquent ORM 通过动态属性访问一对一关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16888029/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com