laravel groupBy技巧

这里记录一个laravel groupBy技巧

      • 1.groupBy 报错
      • 2.groupBy 连接分组内容(group_concat)

1.groupBy 报错

SQLSTATE[42000]: Syntax error or access violation: 1055 Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregated column which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by

是由于mysql默认开启严格模式,当select字段比group by使用到的字段多的时候,会报错。
可以减少多余的select的字段,或者关闭严格模式

解决方法是在laravel的 config/database.php 中设置 strict 为false,关闭严格模式。
当然关闭严格模式会有一些其他的影响,比如varchar字符长度超过了指定的长度,会截取到指定长度,而不会报错等

2.groupBy 连接分组内容(group_concat)

$goods = DB::table('shop_goods')
        ->join('shop_store','shop_goods.store_id','shop_store.id')
        ->leftjoin('shop_goods_sku','shop_goods.id','shop_goods_sku.gid')
        ->select('shop_goods.id','shop_goods.name','shop_store.storename',DB::raw('group_concat(kou_id) as kou_id'))
        ->groupBy('shop_goods.id')
        ->get()->toArray();

结果如下:
laravel groupBy技巧_第1张图片

你可能感兴趣的:(laravel,laravel,mysql)