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

Laravel使用模型查询构造器时如何保留重复ID对应的重复记录

解决方案

你可以利用 Laravel 集合的 keyBy + map 组合实现,仅执行1次SQL查询,代码简洁且性能损耗极低:

// 原始带重复值的ID数组
$userIds = $userIdsQuery->pluck('user_id');

// 仅查询唯一ID对应的用户,将集合键设置为用户ID方便O(1)查找
$uniqueUsers = User::whereIn('id', $userIds->unique())->get()->keyBy('id');

// 按原始ID数组的顺序、重复次数映射得到目标结果
$targetUsers = $userIds->map(fn ($userId) => $uniqueUsers->get($userId));

如果需要过滤掉可能不存在的无效ID对应空值,可以在map后链式调用->filter()。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 18:06:01