gpt4 book ai didi

laravel - 根据子存在和列值过滤多对多关系

转载 作者:行者123 更新时间:2023-12-02 00:54:47 26 4
gpt4 key购买 nike

我已经搜索了一段时间,找不到答案,这就是我所拥有的:

1- ShowCategory (id & title)

class ShowCategory extends Model
{
public function shows()
{
return $this->belongsToMany(Show::class, 'category_show');
}
}

2- 显示 (id, title & active)

class Show extends Model
{
public function categories()
{
return $this->belongsToMany(ShowCategory::class, 'category_show');
}
}

因此存在多对多关系,我需要的是检索所有至少有一个与之相关的节目的 ShowCategory 元素,并通过 show.active 过滤每个 ShowCategory->shows,只返回事件的节目

这是我正在尝试做的事情:

 $categories = ShowCategory::whereHas('shows', function($query) {
$query->where('shows.active', '=', true);
})->get();

它只过滤包含节目的 ShowCategory,如果其中只有一个节目处于事件状态,它会返回包含所有节目的类别,即使其他节目不活动,我也需要过滤那些不活动的。

我该怎么办?提前致谢

最佳答案

这需要 whereHas()with() 的组合。首先,whereHas() 会将 ShowCategory 模型过滤为那些具有事件 Show 的模型,而 with() 子句将关系的结果限制为仅返回 active 的结果:

$categories = ShowCategory::whereHas("shows", function($subQuery) {
$subQuery->where("shows.active", "=", true); // See note
})->with(["shows" => function($subQuery){
$subQuery->where("shows.active", "=", true);
}])->get();'

注意:您应该能够使用 active 而不是 shows.active,但这取决于该列是否在多个表中。

使用此查询,您将获得 ShowCategory 模型的 Collection,每个模型都有其事件的 Show 模型已经加载并可通过 ->显示:

foreach($categories AS $category){
dd($category->shows); // List of `active` Shows
}

关于laravel - 根据子存在和列值过滤多对多关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55065229/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com