0

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'
  • This is what can help you build right Active query: https://laravel.com/docs/8.x/queries#or-where-clauses – Serghei Leonenco Mar 18 '21 at 05:14
  • yes, whenever you need a parenthesis, that will translate to a closure in Laravel Eloquent. So your 2 parentheses will need 2 closures like some answers below. – Anurat Chapanond Mar 18 '21 at 05:43

3 Answers3

0

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

Andrew
  • 1,745
  • 1
  • 21
  • 29
0

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

Basharmal
  • 1,313
  • 10
  • 30
0

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();
Hedayatullah Sarwary
  • 2,664
  • 3
  • 24
  • 38