【发布时间】:2020-12-15 02:11:37
【问题描述】:
我有三个模型和关系。发布,用户配置文件,用户。我需要从用户表中获取名称列值,但我需要通过帖子和用户配置文件来获取它。帖子与用户个人资料相关联,用户个人资料与用户相关联。我试过 $post->userProfile()->user()->name 但它不起作用。我得到错误
Call to undefined method Illuminate\\Database\\Eloquent\\Relations\\BelongsTo::user()
这是我的代码。任何帮助表示赞赏。
Post.php
posts 表有 user_profile_id 列
public function userProfile()
{
return $this->belongsTo(UserProfile::class);
}
用户配置文件.php
public function user()
{
return $this->belongsTo(User::class, 'id');
}
public function posts()
{
return $this->hasMany(Post::class);
}
用户.php
public function profile()
{
return $this->hasOne(UserProfile::class, 'id');
}
【问题讨论】:
-
什么是
$posts?单个帖子还是收藏? -
@Lessmore Single post.
-
如果
profile()在 User.php 中更改为userProfile()会发生什么 -
不要使用括号,使用$post->userProfile->user->name