Sivo 悉见

laravel 报错this is incompatible with sql_mode=only_full_group_by

匿名 · 更新于 2019/9/25

laravel操作数据库的时候有时候会发现如下错误:

SQLSTATE[42000]: Syntax error or access violation: 
1055 Expression #2 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'vuespa.messages.user_id' which is not functionally dependent on columns in GROUP BY clause;
this is incompatible with sql_mode=only_full_group_by (SQL: select type,user_id,see,count(*) as count from `messages` group by `type` having `see` = 0 and `user_id` = 1)

这是因为laravel mysql数据库开启了严格模式,导致很多mysql语句可能会报错,
方法一(推荐)
仅选择聚合的列 ,如下:

Product::selectRaw('store_id')
        ->where('status', 1)
        ->groupBy('store_id')
        ->get();


方法二
我们可以将其关闭即可

找到config/database.php,修改'strict' => true,改为false即可

 
 

 

方法三
通过在config / database.php文件中设置模式来解决它。

设置方式如下:

'modes'  => [
                'STRICT_TRANS_TABLES',
                'NO_ZERO_IN_DATE',
                'NO_ZERO_DATE',
                'ERROR_FOR_DIVISION_BY_ZERO',
                'NO_ENGINE_SUBSTITUTION',
            ]

用于mysql驱动程序

'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' => true,
        'engine' => null,
        'modes'  => [
            'ONLY_FULL_GROUP_BY', //注释该行即可
            'STRICT_TRANS_TABLES',
            'NO_ZERO_IN_DATE',
            'NO_ZERO_DATE',
            'ERROR_FOR_DIVISION_BY_ZERO',
            'NO_ENGINE_SUBSTITUTION',
        ]
    ],
通过'ONLY_FULL_GROUP_BY'从列表中删除起作用