D
D
danilduck2017-10-03 20:17:03
MySQL
danilduck, 2017-10-03 20:17:03

Why doesn't GROUP BY work in Laravel 5?

I am writing a query using Laravel. I can't handle the GROUP BY method.
Here is a MySQL query that works fine in the console:

SELECT users.*, sum(payments.amount) as sum_p 
FROM users as users
LEFT JOIN payments as payments ON payments.user_id=users.id
WHERE payments.amount>0 AND payments.to_user_id=1 AND payments.status='success'
GROUP BY users.id ORDER BY sum_p DESC;

And here is the version with the interpreter:
User::selectRaw('users.*, SUM(payments.amount) as sum_p')
            ->join("payments", 'payments.user_id', 'users.id')
            ->where('payments.status', 'success')
            ->where('payments.amount', '>', '0')
            ->where('payments.to_user_id', $user->id)
            ->groupBy('users.id')->orderBy('sum_p', 'desc')
            ->get();

Which gives Syntax error or access violation: 1055 'laravel_project.users.name' isn't in GROUP BY .
But if in selectRaw we change users.* to user.id (as in groupBy), everything will work fine, but, of course, it will give me only two columns: users.id and sum_p, and not the User model completely. How to bypass it? What? I do not understand?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
Eugene Wolf, 2017-10-03
@danilduck

File /config/database.php , line 53: 'strict' => true,(in the "section" 'mysql'), change the value to false .
Details:
59d3c7f6588c1557458510.png

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question