@JLRDW - Thank you both for your responses!
I've opened a thread here: https://laracasts.com/discuss/channels/eloquent/weird-behaviour-on-paginating-with-join-and-having-clause
I've come to a weird conclusion... having actually works fine just the way I stated it, but what causes the issue is the paginator! That means, that error is only being thrown when I add ->paginate(10) instead of ->get() at the end of the query... Any ideas why? Here's the query.
Works perfectly:
$orders = App\Order::leftJoin('revenues', function($j){ return $j->on('orders.id', '=', 'revenues.order_id')->where('revenues.is_paid', true);})
->havingRaw('price_to_customer - (case when abs(sum(revenues.price)) < 1 then null else sum(revenues.price) end) > ?', [0])
->groupby('orders.id')
->get();
Doesn't work:
$orders = App\Order::leftJoin('revenues', function($j){ return $j->on('orders.id', '=', 'revenues.order_id')->where('revenues.is_paid', true);})
->havingRaw('price_to_customer - (case when abs(sum(revenues.price)) < 1 then null else sum(revenues.price) end) > ?', [0])
->groupby('orders.id')
->paginate(15);
Error thrown:
Column not found: 1054 Unknown column 'price_to_customer' in 'having clause' (SQL: select count(*) as aggregate from `orders` left join `revenues` on `orders`.`id` = `revenues`.`order_id` and `revenues`.`is_paid` = 1 group by `orders`.`id` having price_to_customer - (case when abs(sum(revenues.price)) < 1 then null else sum(revenues.price) end) > 0)
I didn't want to invade this topic, we can continue anew in my thread. Thank you a lot for your support!