我有以下关系:
这些是我在匹配模型中的关系:
user.php的
public function assignments()
{
return $this->belongsToMany('Assignment')->withPivot('is_finished')->withTimestamps();
}
Assignment.php
public function badges()
{
return $this->belongsToMany('Badge', 'badge_assignment')->withTimestamps();
}
Badge.php
public function assignments()
{
return $this->belongsToMany('Assignment', 'badge_assignment')->withTimestamps();
}
我正在尝试获取用户已完成作业的所有徽章。这是我的疑问:
$user = User::with(array(
'assignments' => function($query) {
$query->where('is_finished', '=', true)->orderBy('updated_at', 'desc');
})
)
->with('badges')
->username($name)->first();
然而,当我使用foreach($ user-> assignments->徽章......)时,这会产生错误“调用未定义的方法Illuminate \ Database \ Query \ Builder :: badges()”。
然后我尝试在第一个范围内获得徽章,但我不知道如何到达is_finished:
$user = User::with(array(
'assignments.badges' => function($query) {
$query->where('is_finished', '=', true)->orderBy('updated_at', 'desc');
})
)
->username($name)->first();
有了这个,我得到“未找到列”,因为查询在徽章中寻找is_finished,而不是assignment_user关系。
当我遇到这个问题时,我试着确定一下:
User::with('assignments.badges')->whereUsername($username);
...而且我仍然会收到“Undefined property:Illuminate \ Database \ Eloquent \ Collection :: $ badges”。
我做错了什么?
答案 0 :(得分:1)
您需要像这样加载嵌套assignments.badges
:
$user = User::with(array(
'assignments' => function($query) {
$query->where('is_finished', '=', true)->orderBy('updated_at', 'desc');
})
)
->with('assignments.badges')
->username($name) // do you have a scope for this or should it be whereUsername?
->first();