laravel groupBy技巧

这里记录一个laravel groupBy技巧

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();

结果如下:
示例结果

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小阿巳

你的鼓励就是我最大的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值