Php Laravel中的链接关系问题
我有三个模型和关系。Post、UserProfile、User。我需要从users表中获取name列值,但我需要遍历posts和user profile来获取它。帖子连接到用户配置文件,用户配置文件连接到用户。我尝试了$post->userProfile()->user()->name,但它不起作用。我犯了一个错误Php Laravel中的链接关系问题,php,laravel,Php,Laravel,我有三个模型和关系。Post、UserProfile、User。我需要从users表中获取name列值,但我需要遍历posts和user profile来获取它。帖子连接到用户配置文件,用户配置文件连接到用户。我尝试了$post->userProfile()->user()->name,但它不起作用。我犯了一个错误 Call to undefined method Illuminate\\Database\\Eloquent\\Relations\\BelongsTo::user() 这是我的
Call to undefined method Illuminate\\Database\\Eloquent\\Relations\\BelongsTo::user()
这是我的密码。感谢您的帮助
Post.php
posts表具有user\u profile\u 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
请试试这个
// Lets get the post having id 1
$post = Post->find(1);
$post->userProfile->user->name;
当你使用括号时,你会得到有说服力的关系本身,而不是那种关系的结果
$post->userProfile()
如果您想通过使用括号获取该帖子的用户配置文件信息,请使用以下代码
$post->userProfile()->get(); //or
$post->userProfile()->first();
什么是
$posts
?单个帖子或集合?@Lessmore Single post。如果User.php中的profile()
更改为userProfile()
,会发生什么情况?若不使用括号,请使用$post->userProfile->User->name