Laravel使用groupBy后仍报“select列表未在group by子句中”错误求助
解决Laravel Eloquent GroupBy报错问题
报错原因
你的查询使用groupBy后调用get(),默认会查询表中所有字段,但MySQL开启ONLY_FULL_GROUP_BY模式时,要求SELECT语句中的字段必须要么出现在GROUP BY列表中,要么被聚合函数(如MAX()、COUNT())处理,否则就会抛出select list is not in group by clause and contains nonaggregated column错误。
解决方案
1. 明确指定查询字段(推荐)
只查询GROUP BY包含的字段,或者添加聚合函数处理其他字段,修改后的代码如下:
$all_ps = Palletstock::select('palletpart','location','supplier_code', 'qty') ->where('status', 0) ->where(function($query) use ($search) { $query->where('palletpart', 'like', '%'.$search.'%') ->orWhere('location', 'like', '%'.$search.'%') ->orWhere('supplier_code', 'like', '%'.$search.'%') ->orWhere('qty', 'like', '%'.$search.'%'); }) ->offset($start) ->limit($length) ->groupBy('palletpart','location','supplier_code', 'qty') ->get();
如果需要获取其他字段,比如每个分组的记录数或最新ID,可使用聚合函数:
use Illuminate\Support\Facades\DB; $all_ps = Palletstock::select( 'palletpart','location','supplier_code', 'qty', DB::raw('COUNT(*) as record_count'), DB::raw('MAX(id) as latest_id') ) ->where('status', 0) ->where(function($query) use ($search) { $query->where('palletpart', 'like', '%'.$search.'%') ->orWhere('location', 'like', '%'.$search.'%') ->orWhere('supplier_code', 'like', '%'.$search.'%') ->orWhere('qty', 'like', '%'.$search.'%'); }) ->offset($start) ->limit($length) ->groupBy('palletpart','location','supplier_code', 'qty') ->get();
2. 关闭MySQL严格模式(不推荐)
修改config/database.php中的MySQL配置,关闭严格模式或者移除ONLY_FULL_GROUP_BY:
'mysql' => [ // 其他配置... 'strict' => false, // 或者自定义sql_mode,移除ONLY_FULL_GROUP_BY 'modes' => [ 'STRICT_TRANS_TABLES', 'NO_ZERO_IN_DATE', 'NO_ZERO_DATE', 'ERROR_FOR_DIVISION_BY_ZERO', 'NO_ENGINE_SUBSTITUTION', ], ],
注意:这种方法违背SQL标准,可能导致数据不一致,仅适合临时测试,不建议在生产环境使用。
内容的提问来源于stack exchange,提问作者leviya
相关产品推荐
相关产品推荐

