Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Group by not working after upgrading to laravel 5.3

This is the code that was working on laravel 5.2

$menus = CmsMenuItem::groupBy('menu_id')->get();

but now it throws error

SQLSTATE[42000]: Syntax error or access violation: 1055 Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'convertifier_cms.cms_menu_items.id' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by (SQL: select * from 'cms_menu_items' group by 'menu_id')

I have also tried

 `strict => false` 

in database.php but no effect

like image 728
msonowal Avatar asked Sep 06 '16 09:09

msonowal


People also ask

Why group by is not working in Laravel?

Go to your config/database. php folder. In mysql configuration array, change strict => true to strict => false, and everything will work nicely.

What is strict mode in Laravel database?

"Strict mode," which is really just the list of modes 5.7 enables by default, is comprised of the following modes: ONLY_FULL_GROUP_BY STRICT_TRANS_TABLES NO_ZERO_IN_DATE NO_ZERO_DATE ERROR_FOR_DIVISION_BY_ZERO NO_AUTO_CREATE_USER NO_ENGINE_SUBSTITUTION. You can learn more about these modes at the MySQL documentation.

What is group by in Laravel?

The groupBy() method in Laravel returns the query results by grouping the data of a database table. Suppose we have multiple data of the same type or name in our database. We can get those specific types of data without any duplicate value by using the groupBy() method.

What is group by in MySQL?

The GROUP BY statement groups rows that have the same values into summary rows, like "find the number of customers in each country". The GROUP BY statement is often used with aggregate functions ( COUNT() , MAX() , MIN() , SUM() , AVG() ) to group the result-set by one or more columns.


2 Answers

Try this for database config.

 'mysql' => [
            'driver' => 'mysql',
            'host' => env('DB_HOST', 'localhost'),
            'port' => env('DB_PORT', '3306'),
            'database' => env('DB_DATABASE', 'forge'),
            'username' => env('DB_USERNAME', 'forge'),
            'password' => env('DB_PASSWORD', ''),
            'charset' => 'utf8',
            'collation' => 'utf8_unicode_ci',
            'prefix' => '',
            'strict' => false,
            'engine' => null,
        ],

and use query like this way

$menus =DB::table('cms_menu_item')
    ->select('*')
    ->groupBy('menu_id')
    ->get();
like image 88
Nil Avatar answered Oct 21 '22 08:10

Nil


As per this PR just try this in your database config

'strict' => false,

If not there is some known issue is going on.

Please refer these links PR & Issue

like image 37
vijaykumar Avatar answered Oct 21 '22 07:10

vijaykumar