我有三个模型和关系。帖子,UserProfile,用户。我需要从用户表中获取名称列值,但是我需要遍历帖子和用户个人资料来获取它。帖子已连接到用户个人资料,而用户个人资料已连接到用户。我尝试了$ post-> userProfile()-> user()-> name,但是它不起作用。我得到错误
Call to undefined method Illuminate\\Database\\Eloquent\\Relations\\BelongsTo::user()
这是我的代码。任何帮助表示赞赏。
Post.php
帖子表具有user_profile_id列
public function userProfile()
{
return $this->belongsTo(UserProfile::class);
}
UserProfile.php
public function user()
{
return $this->belongsTo(User::class, 'id');
}
public function posts()
{
return $this->hasMany(Post::class);
}
User.php
public function profile()
{
return $this->hasOne(UserProfile::class, 'id');
}
您可能想使用动态属性来访问实际的已解决关系(模型或集合),而不是关系方法:
$post->userProfile->user->name
这将假定这些关系已正确设置并且存在于数据库中。
如果您使用的是PHP8,则可以使用存在操作符来避免关系返回null
和调用方法的问题:
$post->userProfile?->user?->name
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句