Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

alihoushyaripour's avatar

What is this eloquent problem?

Hi,

I have two model, 'User' and 'Activity' that every user has many activities.

This is my eloquent query:

return Activity::select(['users*', DB::raw('sum(activities.coin) as coin')])
            ->leftJoin('users', 'users.id', '=', 'activities.user_id')
            ->where(['activities.active' => true])
            ->whereDate('activities.created_at', '>=', $date)
            ->groupBy(DB::raw('coin'))
            ->havingRaw('coin > 0')
            ->orderByRaw('coin', 'desc')
            ->skip(0)
            ->take(20)
            ->distinct()
            ->get();

I want to get all users data with sum of users coin, and show me this error:

"SQLSTATE[23000]: Integrity constraint violation: 1052 Column 'coin' in group statement is ambiguous (SQL: select distinct *, sum(user_activities.coin) as coin from `user_activities` left join `users` on `users`.`id` = `user_activities`.`user_id` where (`user_activities`.`active` = 1) and date(`user_activities`.`created_at`) >= 2017-07-19 11:56:55 group by coin having coin > 0 order by coin limit 20 offset 0)"
0 likes
1 reply
martinbean's avatar

@alihoushyaripour Did you read the error message? It’s telling you exactly what the issue is: Column 'coin' in group statement is ambiguous.

That means you have more than one coin column, and you have to be explicit as to which one you want to use by also specifying the table, i.e. activities.coin.

2 likes

Please or to participate in this conversation.