2

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;

1 Answer 1

4

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();
Sign up to request clarification or add additional context in comments.

2 Comments

My 2 cents for current OP or future readers - use the scope approach. Using the clone approach will work fine, but has the higher chance of future bugs if a dev modifies things without fully understanding why the clone is needed.
@BrianThompson 100% agreed! I added the clone approach to attempt to illustrate why they were getting the results (from their suspicion, "[...] as if the $result2 query has the 2 conditions null and not null"), but using a scope is definitely the preferred approach. Cheers!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.