The best way to debug this is using the debugbar to see what the actual query is. When using relationships, Laravel runs multiple queries because it will first fetch the ids and use those for the next query to get the relationship. So when you use toSql it's probably not the final/only query!
toSql() returning "incorrect" query
Hello
I have the following code:
public function activeCoupons()
{
return $this->coupons()->active();
}
public function coupons()
{
return $this->hasManyThrough(Coupon::class, Saving::class);
}
If I dd($this->coupons()->active()->toSql()); the query I get starts like this:
select * from `coupons` inner join `savings` ...
However, the query that really runs (which you can see in the Laravel error debug page if you add an error to the query on purpose) is:
select `coupons`.*, `savings`.`shop_id` from `coupons` inner join `savings` ...
Quite different as you can see!
Is this on purpose or is it a bug? And if it's the former, what it the logic of this behavior?
I was trying to add a raw select to the query but it was producing incorrect results. When trying to debug with toSql() I couldn't find the problem, as the query that toSql() was giving me was not the one that was really running.
Please or to participate in this conversation.