0

I have query like this

$query = MyModel::query()->where('status', 1);

and I want to get a different output

$result1 = $query->where('type', 1)->count();
$result2 = $query->where('type', 2)->count();
$result3 = $query->where('type', 3)->count();

result for $result2 and $result3 is wrong. So I try to get the raw queries from this

$result1 = $query->where('type', 1)->toSql();
$result2 = $query->where('type', 2)->toSql();
$result3 = $query->where('type', 3)->toSql();

the raw query shows

select * from `my_table` where `status` = ? and `type` = ?
select * from `my_table` where `status` = ? and `type` = ? and `type` = ?
select * from `my_table` where `status` = ? and `type` = ? and `type` = ? and type = ?

why Laravel added the where condition to $result2 and $result3?

  • 2
    Probably because you're building on `$query` multiple times and it's stacking the where clauses – Andy Holmes Jul 04 '23 at 21:57
  • 1
    add ``clone`` keyword before every query your query relations are being stacked on top of each query hence ``and`` is showing on query which will result in incorrect results – Sumit kumar Jul 05 '23 at 13:36

0 Answers0