Laravel模型使用groupby函数报错
环境
Laravel版本:7.0
MySQL版本:5.7.26
php 7.2
MySQL报错如下:
SQLSTATE[42000]: Syntax error or access violation: 1055 Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'tp_6.article.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 article group by user_id)
产生原因:
由于
mysql
默认开启严格模式,当select
字段比group by
使用到的字段多的时候,会报错。解决方案:
在laravel的
config/database.php
中设置strict
为false
,关闭严格模式,如下图:
ps : 关闭严格模式会有一些其他的影响,比如varchar字符长度超过了指定的长度,会截取到指定长度,而不会报错等
特别感谢
本作品采用《CC 协议》,转载必须注明作者和本文链接