Laravel Mysql GROUP BY 查询常见问题

Laravel 框架中对 Mysql 查询复查语句的时候,有时候会遇到sql在MySQL终端中运行没问题,但是在laravel中出现错误.

  • 举个🌰

查询表中name有重复的数据

1
2
3
$sql = " `name` IN (SELECT `name` FROM clients child GROUP BY child.`name` HAVING COUNT(child.`name`) > 1 ) ORDER BY `name`";

$clients = Client::whereRaw($sql)->paginate();

通过toSql()将sql打出来放到mysql终端中执行是没有问题的,但是在laravel框架中则会出现:

Mixing of GROUP columns (MIN(),MAX(),COUNT(),...) with no GROUP columns is illegal if there is no GROUP BY clause

  • 解决办法

config/database.php中mysql的 strict改为false就可以啦!