在我的 laravel 5.2 Web 应用程序中,我有以下三个表 -
用户
id
username
个人资料
id
user_id
个人资料图片
id
profile_id
概述我的场景 - 一个用户可以有一个个人资料(一对一),一个个人资料可以有许多个人资料图像(一对多)。这些具有相关关系函数的表的模型是-
User.php
public function profile_images(){
$this->hasManyThrough('App\ProfileImage', 'App\Profile');
}
public function profile(){
return $this->hasOne('App\Profile');
}
Profile.php
public function profile_images()
{
return $this->hasMany('App\ProfileImage');
}
public function user()
{
return $this->belongsTo('App\User');
}
ProfileImage.php
public function profile()
{
return $this->belongsTo('App\Profile');
}
我的问题 当我在用户模型上调用 profile_images() 时,我仅获取用户数据以及配置文件和 profile_images 的列名称。即使我有一个配置文件(具有与我的测试用例匹配的 user_id)和两个具有匹配的 profile_id 的 profile_image,也不会返回任何属性/数据。
你能帮忙吗?我假设这是我的 hasManyThrough 使用的问题。
谢谢
最佳答案
没有。您的 hasManyThrough 关系很好,但是当您调用 profile_images
方法时,它会返回 QueryBuilder 实例。要获取相关模型的集合,请使用 get
方法
$images = $user->profile_images()->get();
或者只是使用 laravel 的“魔法”
$images = $user->profile_images;
关于php - Laravel 5.2 Eloquent ORM hasManyThrough,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37466427/