Try replacing where with having.
Feb 1, 2017
6
Level 1
Issues with Eloquent using with(), groupBy() and sum()
I have got my relationships correctly set in the models. I like that I do not have to join any tables manually and that I can eager load when it calls for. However, I am having a hard time converting an SQL query into Eloquent.
The RAW SQL query:
SELECT a.id, SUM(a.revenue) as total, b.email, c.name, d.name as poc
FROM partner_revenues a
INNER JOIN lp_users b ON a.id = b.id
INNER JOIN partners c ON a.partner_id = c.id
INNER JOIN pocs d ON a.poc_id = d.id
GROUP BY a.user_id
The Eloquent code:
$totalRevenue = PartnerRevenue::with([
'partner' => function($query) {$query->select('id', 'partner_id');},
'poc' => function($query) {$query->select('id', 'poc_id');},
'user' => function($query) {$query->select('id', 'id');}])
->groupBy('user_id')
->where('accepted', 1)
->sum('revenue');
That does not work. What am I doing wrong?
Level 75
Eager load is more for simple relation, orders / order details, that sort of thing, a group by, all have to be checked for sql to get grouping.
2 likes
Please or to participate in this conversation.