laravel 去重问题

$coupon->whereIn('id',$res1['coupon_id'])->where('status',2)->get();

//怎么根据merchant_id 来去重

我尝试了

$coupon->whereIn('id',$res1['coupon_id'])->where('status',2)->groupBy('merchant_id')->get();

结果是
SQLSTATE[42000]: Syntax error or access violation: 1055 Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'run.pq_coupon.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 pq_coupon where pq_coupon.deleted_at is null group by merchant_id)

阅读 12.2k
8 个回答

编辑 config/database.php 第53行 strict的值改成false,我的是5.5的在53行,你看下你的在第几行,['connections']['mysql']['strict'], 路径是这样的

如果groupBy不行的话, distict 又该如何书写代码?

use DB;

$coupon->select(DB::Raw('DISTINCT(merchant_id)')->whereIn('id',$res1['coupon_id'])->->where('status',2)->get();

groupby放在get后面

这个提示不是说了吗?
你的数据库mode有 only_full_group_by 这个就要求你不能用select * 了。
你试试修改数据库的mode
先 select @@sql_mode;
然后把 only_full_group_by 删掉;
如果你不能删的话,就按阿泽说的方法做。

审题

题注的需求描述的不是特别清楚,所以根据现有的信息我来完整描述下题主的需求。

题主的表: pq_coupon table , 有几个核心字段 id,status,merchant_id

题主尝试的查询写法:

$coupon->whereIn('id',$res1['coupon_id'])->where('status',2)->groupBy('merchant_id')->get();

$coupon->whereIn('id',$res1['coupon_id'])->where('status',2) 会找出一批优惠券数据,但是其中 merchant_id 存在很多重复的值。

所以题主想 每个店铺下(merchant_id) 只找出一条优惠券即可。

不知道是否理解正确,正确了再说解题方法。

找到 config/database.php 文件中的 connections -> mysql ;
strict 改为 false ;

具体可以参考 最适合入门的Laravel初级教程(六)

如果你想 知其所以然 ;
我给你个关键字 only_full_group_by ;
百之谷之必应之;
搜索一遍你就懂了;

楼主可以这样去重, Goods::get()->groupBy('userid');

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题