Laravel WhereIn为AND而不是OR

时间:2019-07-20 01:10:26

标签: laravel

假设我有一个数组:[2,3,4]

(数组长度/数组中值的数量更改,因此我无法使用其中的位置对其进行硬编码)

在查询关系时,我只想获取包含数组中所有值的项目。

我知道WhereIn并像这样使用它:

 ->whereHas('interests', function($query) use ($arrayIds) {
     $query->whereIn('interest_id', $arrayIds);
 })

但这基本上是

orWhere()->orWhere->get();

我如何实现以下行为:

->where()->where()->get();

因此,使用ID数组时,数组中的所有值都必须匹配?

2 个答案:

答案 0 :(得分:1)

我将与用户和俱乐部回答。如果用户可以属于多个俱乐部,这将为您提供属于俱乐部2 AND俱乐部3 AND俱乐部4的用户:

$clubIds = [2,3,4];     // club IDs
$users = User::query(); // initialize the query

// loop over club IDs, and give a whereHas clause for each one
foreach($clubIds as $clubId) {
    $users = $users->whereHas('clubs', function($clubQuery) use ($clubId) {
        // specify "clubs.id" to avoid ambiguity
        $clubQuery->where('clubs.id', $clubId); 
    });
}

$users = $users->get(); // execute the query

答案 1 :(得分:0)

我不确定为什么要在ID上使用AND,但是可以像这样循环遍历ID:

 ->whereHas('interest_id', function($query) use ($arrayIds) {
    foreach($arrayIds as $id){
        $query->where('id', $id);
    }
 })