简体   繁体   中英

Eloquent With Nested Where Clauses

I am curious if there is a way using Eloquent's query builder to nest where clauses or if I should just run a raw DB query.

Here is the raw query:

SELECT * FROM `inventory` WHERE (`sold_date` > '2020-12-31' OR `sold_date` IS NULL) AND (`removed_date` > '2020-12-31' OR `removed_date` IS NULL) AND `category` <> 1 AND `purchased_date` <= '2020-12-31'

Yes you can pass an array with conditions into to Eloquent's where() and have multiple where() s.

See this answer (including the comments) for how you could build your query: https://stackoverflow.com/a/27522556/4517964

You can try this

    Inventory ::where(function($query) use ($d1){
                $query->where('solid_date','=',$d1)
               ->orWhereNull('solid_date');
           })->where(function($query2) use ($da1){
                $query2->where('removed_date','=',$da1)
               ->orWhereNull('removed_date');
          })->where(function($query3) use (){
                $query2->where('category','<>',1)
               ->where('purchased_date','=','2020-12-31');
          }}->get();

I perfer to use parameter in few functions may be you will need it otherwise you can hard code it like I did in the last function

In Laravel Eloquent you can use the below query:

$inventory = Inventory::where(function($query) {
    $query->where('sold_date', '>', '2020-12-31')->orWhereNull('sold_date');
})->where(function($query) {
    $query->where('removed_date', '>', '2020-12-31')->orWhereNull('removed_date');
})->where('category', '<>', 1)->where('purchased_date', '<=', '2020-12-31')
->order('id', 'DESC')
->get();

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