You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Laravel Eloquent获取唯一user_id数据?distinct方法失效

解决Laravel Eloquent获取唯一user_id的问题

你的distinct('user_id')不生效的核心原因是:MySQL的DISTINCT关键字是作用于所有返回列的,而非单个指定列。当你默认查询Plot表的全部字段,再关联user模型时,即使user_id相同,只要其他Plot字段有差异,整条记录会被判定为不同,DISTINCT就无法过滤掉重复的user_id。

下面提供几种可行的解决方案:

方案1:先获取唯一user_id,再查询关联用户

如果你的需求只是获取拥有有效Plot的唯一用户,不需要Plot的具体数据,可以先提取唯一的user_id集合,再查询User模型:

// 提取所有有效Plot的唯一user_id
$userIds = Plot::active()
    ->whereNotNull('user_id')
    ->distinct()
    ->pluck('user_id');

// 根据user_id查询用户并分页
$users = User::whereIn('id', $userIds)->paginate(10);

方案2:使用groupBy分组user_id

如果需要保留Plot模型的结构,且每个user_id只返回一条Plot记录,可以用groupBy('user_id')。注意MySQL严格模式下,分组查询的字段要么是分组字段,要么是聚合函数,所以需要指定查询列或使用聚合函数:

// 只保留每个user_id对应的最新Plot记录(用MAX(id)确保取最新条目)
$list = Plot::active()
    ->whereNotNull('user_id')
    ->selectRaw('MAX(id) as id, user_id, MAX(created_at) as created_at') // 添加需要的Plot字段及对应聚合函数
    ->groupBy('user_id')
    ->with('user')
    ->paginate(10);

如果需要更多Plot字段,可在selectRaw中添加对应的聚合函数(如MIN(status)、MAX(title)等)。

方案3:指定查询列配合distinct

如果只需要user_id和关联的用户信息,可以明确指定查询user_id字段,此时distinct会针对该字段生效:

$list = Plot::active()
    ->whereNotNull('user_id')
    ->select('user_id')
    ->distinct()
    ->with('user')
    ->paginate(10);

内容的提问来源于stack exchange,提问作者mahbub

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.28 12:57:09