Laravel得到一个查询,检查QueryBuilder是否存在至少两个关系中的一个,而不忽略其他过滤器



我有一个模型从属关系hasMany()与Activities和Transfers

我现在过滤我的附属机构,并希望检索附属机构至少有1个活动或至少一个转移(它可以有0个活动和1个转移,将通过)。此外,我必须忽略给定的无效从属id数组

this is what I try

$affiliates = Affiliate::whereNotIn('id',$invalidIds);
if ($params['sales']){
$affiliates = $affiliates->whereHas('activities', static function (Builder $builder) use ($params) {
$builder->where('status','>',0)
->where('status','<',8)
;  
})->orWhereHas('transfers', static function (Builder $builder) use ($params) {
$builder->where('status','>',0)
->where('status','<',8)  
;
});
}
$affiliates = $affiliates->get();

使用whereHas和orWhereHas应该工作,但我认为的问题是,在orWhereHas()中,它目前忽略了其他过滤器(在这种情况下,过滤器忽略了附属机构的$invalidIds),所以我得到附属机构至少有一个活动或一个转移,但我不忽略无效的id

我做错了什么吗?或者有不同的方法来解决这个问题?

试试这个:

$affiliates = Affiliate::whereNotIn('id',$invalidIds);
if ($params['sales']){
$affiliates = $affiliates->where(function($query){
$query->whereHas('activities', function ($q1){
$q1->where('status','>',0)->where('status','<',8);
})
->orWhereHas('transfers',function ($q2){
$q1->where('status','>',0)->where('status','<',8);
});
});
}
$affiliates = $affiliates->get();

我不完全确定,但我认为玩弄方法顺序将工作。

$affiliates = Affiliate::query();
if ($params['sales']) {
$affiliates = $affiliates->whereHas('activities', static function (Builder $builder) use ($params) {
$builder->where('status', '>', 0)
->where('status', '<', 8);
})->orWhereHas('transfers', static function (Builder $builder) use ($params) {
$builder->where('status', '>', 0)
->where('status', '<', 8);
});
}
$affiliates = $affiliates->whereNotIn('id', $invalidIds)->get();

最新更新