具有OR WHERE条件的Laravel雄辩查询

时间:2020-05-01 09:28:59

标签: laravel eloquent where-clause

我正在使用Laravel 6和mysql 7

我在下面查询

$tasks = Task::where('deleted_at', null)->where('company_id',$company_id);
$tasks = $tasks->where('created_by',$user_id);
$tasks = $tasks->orWhereIn('id',$task_ids);

当我打印它时,它会在原始查询下面生成

SELECT * FROM `tasks` WHERE `deleted_at` IS NULL AND  `company_id` = 25 AND `created_by` = 20 OR 
`id` IN(112,...215) ORDER BY `id` DESC

虽然我具有where('deleted_at',null)条件,但是它不起作用,但现在ID 112被删除但仍显示在结果中

我也想在$task_ids上应用所有其他条件

如何通过优化查询来实现?

已更新 :这是完整的场景

我想选择所有由我创建或分配给我的记录。这是我完整的代码。

 $tasks = Task::where('deleted_at', null)->where('company_id',$company_id);
 $tasks = $tasks->where('created_by',$user_id);
 $task_ids = TaskUser::where('user_id',$user_id)->pluck('task_id')->all();
 $tasks = $tasks->orWhereIn('id',$task_ids);

1 个答案:

答案 0 :(得分:2)

这是因为AND运算符的precedence比OR高,这基本上意味着AND比OR更能“粘”在一起。您的查询基本上是这样解释的:

SELECT * FROM `tasks` 
WHERE 
    (`deleted_at` IS NULL AND  `company_id` = 25 AND `created_by` = 20) 
  OR 
    ( `id` IN(112,...215) ) 

我不确定您是不是真的想要任何东西。如果您确实想应用所有条件,则只需将orWhereIn更改为whereIn


如果您希望所有未删除的任务属于该公司,并且其ID在列表中,并且属于一个用户或用户,则您需要像这样更新查询:

$tasks = Task::where('deleted_at', null);

$tasks = $tasks->where(function($q) use ($user_id, $task_ids){

    $q->where(function($q2) use ($user_id, $task_ids) {
        $q2->where('created_by',$user_id)
           ->where('company_id',$company_id);
    })
      ->orWhereIn('id',$task_ids);
});

这将导致以下查询:

SELECT * FROM `tasks` 
WHERE `deleted_at` IS NULL AND ( 
  ( `company_id` = 25 AND `created_by` = 20 )
  OR
  `id` IN(112,...215) 
) 

优秀的laravel文档中实际上也有一章关于parameter grouping