There are ways to fix this
#1
Get only the columns we are grouping by, in this case category_id.
NOTE: Columns in select
must be present in groupBy
, and vice versa.
$posts = Post::query()
->select('category_id')
->groupBy('category_id')
->get();
#2
But I want all columns!
Okay, so you want to get all columns. Then the trick is to simply not use groupBy() on a database level. Instead, you can use it with the returned collection instead.
$posts = Post::query()
->get()
->groupBy('category_id');
[
'1' => [
['id' => 1, 'name' => 'Post 1', 'category_id' => 1, 'author_id' => 4 'visits' => 32],
['id' => 2, 'name' => 'Post 2', 'category_id' => 1, 'author_id' => 8 'visits' => 12],
],
'2' => [
['id' => 3, 'name' => 'Post 3', 'category_id' => 2, 'author_id' => 12 'visits' => 201],
['id' => 4, 'name' => 'Post 4', 'category_id' => 2, 'author_id' => 4 'visits' => 0],
],
]
#3
It is possible to simply disable "strict mode" in Laravel, by setting it to false
in the database.php
config file. While possible I cannot recommend doing so. It is better to spend the time learning how to write proper SQL queries, as the results given by turning "strict mode" off, can be unpredictable and lead to problems down the road.
Reference
https://sinnbeck.dev/posts/laravel-groupby-error