I have this Eloquent query:
return DB::table('users')
->leftJoin('bet', function($join) use ($competition_id){
$join->on('users.id', '=', 'bet.user_id');
$join->on('bet.competition_id','=', DB::raw("$competition_id"));
})
->select('users.*', DB::raw('SUM(points) as score'))->get();
it returns me an error:
SQLSTATE[42000]: Syntax error or access violation: 1140 Mixing of GROUP columns (MIN(),MAX(),COUNT(),...) with no GROUP columns is illegal if there is no GROUP BY clause (SQL: select users.*, SUM(points) as score from users left join bet on users.id = bet.user_id and bet.competition_id = 1)
if I just copy-paste the generated SQL (in bold) in PhpMyAdmin, it works perfectly...
Could you please help me solving this issue? because it makes no sense to me...
Thank you
SOLUTION
The problem was just the missing group by:
return DB::table('users')
->leftJoin('bet', function($join) use ($competition_id){
$join->on('users.id', '=', 'bet.user_id');
$join->on('bet.competition_id','=', DB::raw("$competition_id"));
})
->select('users.*', DB::raw('SUM(points) as score'))->groupBy('users.id')->get();
SOLUTION #2
Depending on the version or configuration of MySQL, the solution above is not working and I had to groupBy all the fields as advised by Eric:
return DB::table('users')
->leftJoin('bet', function ($join) use ($competition_id) {
$join->on('users.id', '=', 'bet.user_id');
$join->on('bet.competition_id', '=', DB::raw("$competition_id"));
})
->select('users.*', DB::raw('SUM(points) as score'))
->groupBy('users.id')
->groupBy('users.name')
->groupBy('users.firstName')
->groupBy('users.lastName')
->groupBy('users.email')
->groupBy('users.admin')
->groupBy('users.password')
->groupBy('users.remember_token')
->groupBy('users.created_at')
->groupBy('users.updated_at')->get();
}
->groupBy('users.id).SUM(), but I don't see anyGROUP BYin your statement.GROUP BY. Your query won't even run in all dbms, except for maybeMySQL.