Laravel Eloquent查询构建器组合

时间:2015-12-23 14:23:40

标签: php laravel laravel-4 eloquent laravel-query-builder

所以我需要找到所有ProductionTask belongTo肯定Operation如果

  • 其中'status', '<', 3
  • orWhere('expected_start', '>', $monday_date)

实施orWhereoperation_id的雄辩关系中的Operation列被忽略。

我该怎么办?

这里有错误的代码:

   return production\ProductionTask::where('operation_id', $operation->id)->where('status', '<', 3)->orWhere('expected_start', '>', $monday_date)->and('expected_end', '<', $sunday_date)->get();

1 个答案:

答案 0 :(得分:2)

您需要使用:

return production\ProductionTask::where('operation_id', $operation->id)
     ->where(function($q) use($monday_date) {
         $q->where('status', '<', 3)->orWhere('expected_start', '>', $monday_date);
     }->where('expected_end', '<', $sunday_date)->get();

将您的where条件分组。

使用此功能,您将获得:

SELECT * FROM production_tasks WHERE operation_id = ? AND (status < 3 OR expected_start > ?) AND expected_end < ?

使用以前的方式你会得到这样的东西:

SELECT * FROM production_tasks WHERE operation_id = ? AND status < 3 OR expected_start > ? AND expected_end < ?

它等于:

SELECT * FROM production_tasks WHERE (operation_id = ? AND status < 3) OR (expected_start > ? AND expected_end < ?)
相关问题