【问题标题】:laravel 5.1 : how can i have two wherePivot in eloquent?laravel 5.1:我怎么能有两个 wherePivot 雄辩?
【发布时间】:2017-05-27 06:14:37
【问题描述】:

我需要检查数据透视表上的两个 where 条件。我知道我可以用这个检查一个条件:

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

但是,我想要两个 where 条件。当我使用orWherePivot时,两个where条件是ORed在一起,但我希望它们是ANDed在一起。

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

【问题讨论】:

  • 我喜欢为我的问题添加的唯一一点:在 wherePivot 中的“id”不正确,因为在 where 中有默认的 id。我将其更改为 ->wherePivot('discount_id', $discountId)->wherePivot('used_for_type', null) 并正常工作!

标签: php laravel laravel-5 eloquent laravel-5.1


【解决方案1】:

wherePivot 函数定义如下。所以你可以使用 $boolean 变量作为 'or' 和 'and' 作为加入条件

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() 是调用wherePivot() 的快捷方式,最后一个参数为“or”。 OP 说这不是他们想要的。
【解决方案2】:

wherePivot() 的工作方式与普通的where() 方法相同;你可以只链接第二个wherePivot() 条件,它将与前面的条件一起ANDed:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-30
    • 1970-01-01
    • 2013-09-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多