我参加锦标赛,锦标赛可以有很多>
public function championships()
{
return $this->hasMany(Championship::class);
}
和锦标赛有一个类别。在类别中,我有isTeam
属性。
现在我需要一个能让我获得所有在类别表中都有isTeam = 1
的锦标赛的功能。
public function teamChampionships()
{
}
当然,我已定义:$tournament->championships
,$championship->category
在我的控制器中,我得到了所有这些:
$tournament = Tournament::with('championship.category')->find($tournament->id);
任何想法???
答案 0 :(得分:1)
尝试
$tournament = Tournament::with(['championships' => function ($query) {
$query->whereHas('category', function($subquery) {
$subquery->where('isTeam', '=', 1);
});
}])->get();
如果上述方法不起作用,请尝试其他方法。在类别模型中定义isTeam()
范围
public function scopeIsTeam($query) {
return $query->where('isTeam', 1);
}
然后你可以像这样使用它
$tournament = Tournament::with('championships.categoryIsTeam')
->find($tournament->id);
更好的是,在锦标赛中创建另一个仅加载球队的范围
public function categoryTeam() {
return $this->hasOne(Category::class)->isTeam();
}
抱歉提供太多信息。其中一个应该做的工作。