Laravel Eloquent query builder combination

Ad

So I need to find all ProductionTask that belongTo certain Operation if

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

with implementation of orWhere the column operation_id from eloquent relationship with Operation is being ignored.

What should I do?

Here's the faulty code:

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

Answer

Ad

You need to use:

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();

to group your where conditions.

Using this you will get:

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

Using previous way you were getting something like this:

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

and it equals to:

SELECT * FROM production_tasks WHERE (operation_id = ? AND status < 3) OR (expected_start > ? AND expected_end < ?)
Ad
source: stackoverflow.com
Ad