问题描述
我有一个 Shop
模型,它可以包含三个关系:Specials
、discounts
和 ThrowOuts
。我想选择所有在这三个关系中的任何一个中有数据的 Shop
,但屏蔽那些根本没有的。
Shop::where('state',$state)
->whereHas('Specials')
->whereHas('discounts ')
->whereHas('ThrowOuts')
此查询要求所有关系都有数据 - 不能为空
Shop::where('state',$state)
->orWhereHas('Specials')
->orWhereHas('discounts ')
->orWhereHas('ThrowOuts')
使用 orWhereHas
返回所有在这些关系中具有任何数据的商店不管第一个“where”,所以我也可以得到来自全国各地的商店。
解决方法
...aa我刚刚回答了我自己的问题 - 将第一个 where 的结果分组,然后在该分组上运行关系查询:
Shop::where('state',$state)
->where(function ($query) {
return $query->orWhereHas('Specials')
->orWhereHas('Discounts ')
->orWhereHas('ThrowOuts');
});