Laravel 5.1:如何在Eloquent中使用两个wherePivot?

6

我需要在透视表中检查两个筛选条件。我知道可以通过以下方式检查一个筛选条件:

$dis = $user->discounts()->wherePivot('used_for_id', '=', null)

然而,我想要两个 where 条件。当我使用 orWherePivot 时,这两个 where 条件会被 OR 起来,但我希望它们被 AND 起来。

$whereData = [
    ['id', "=", $discountId],
    ['used_for_id', "=", null]
];

我要为我的问题增加一个观点:因为在 where 中有默认的 id,所以 wherePivot 中的 "id" 不正确。 我将其更改为 ->wherePivot('discount_id',$ discountId)-> wherePivot('used_for_type',null)即可正常工作! - Hamid Naghipour
2个回答

10

wherePivot() 的作用与普通的 where() 方法相同;您可以只是在第二个 wherePivot() 条件后面链接即可,它将与之前的条件进行 AND 运算:

$dis = $user
    ->discounts()
    ->wherePivot('id', '=', $discountId)
    ->wherePivot('used_for_id', '=', null)
    ->get();

4
下面是 wherePivot 函数的定义。因此,您可以使用 $boolean 变量作为“或”和“与”的连接条件。
public function wherePivot($column, $operator = null, $value = null, $boolean = 'and') {   
  //code   
}   

 $dis = $user->discounts()->wherePivot('column', '=', null,'and')      
        ->wherePivot('column', '=', null,'or')       
        ->wherePivot('column', '=', null,'and')     
        ->get();

orWherePivot()是调用带有"or"作为最后一个参数的wherePivot()的快捷方法。OP说这不是他们想要的。 - patricus

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接