简体   繁体   中英

Laravel Eloquent query builder combination

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

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 < ?)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM