Home > OS >  Laravel init query for multiple usage
Laravel init query for multiple usage

Time:03-14

I have this init of query in my model:

$query = Mymodel::where('is_active', 1);

i use it to get different result:

$result1 = $query->where('stat', null)->count();
$result2 = $query->where('stat', '!=', null)->count();

i have 4 rows in my database, 2 of them have stat null and 2 is not null; so i expect that $result1 and $result2 value are 2; but i got that $result1 is 2 and $result2 is 0;

as if the $result2 query has the 2 conditions null and not null;

CodePudding user response:

You can't really use the same query like that. The where clauses will modify the original $query object, so your counts will be a little off.

You should either clone the original, or define it as a Scope:

clone Approach:

$baseQuery = Mymodel::where('is_active', 1);

$result1 = (clone $baseQuery)->whereNull('stat')->count();
$result2 = (clone $baseQuery)->whereNotNull('stat')->count();

scope Approach:

Mymodel.php:

public function scopeActive($query) {
  return $query->where('is_active', 1);
}

Then in your code:

$result1 = Mymodel::active()->whereNull('stat')->count();
$result2 = Mymodel::active()->whereNotNull('stat')->count();

CodePudding user response:

Use whereNull and whereNotNull

$result1 = $query->whereNull('stat')->count();
$result2 = $query->whereNotNull('stat')->count();
  • Related