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

如何提取groupBy查询结果中各分组的唯一值?

提取Laravel查询结果中各列的唯一值

我执行了如下Laravel查询:

Table::select('a','b','c','d')->groupBy('a','b','c','d')->get();

得到的结果集示例如下:

Row1 = a1, b1, c1, d1
Row2 = a1, b1, c1, d2
Row3 = a2, b2, c2, d3
Row4 = a2, null, c3, d4

需要提取每一列的唯一值,最终得到:

$col_a = [a1, a2]
$col_b = [b1, b2, null]
$col_c = [c1, c2, c3]
$col_d = [d1, d2, d3 ,d4]

下面是几种可行的解决方法:

方法一:逐列提取并去重

因为get()返回的是Laravel集合(Collection),可以直接用集合的内置方法处理:

$results = Table::select('a','b','c','d')->groupBy('a','b','c','d')->get();

// 提取各列唯一值并转成数组
$col_a = $results->pluck('a')->unique()->values()->toArray();
$col_b = $results->pluck('b')->unique()->values()->toArray();
$col_c = $results->pluck('c')->unique()->values()->toArray();
$col_d = $results->pluck('d')->unique()->values()->toArray();

各方法作用:

  • pluck('列名'):从集合中取出指定列的所有值
  • unique():去除重复值,会保留null的唯一实例
  • values():重置数组索引,避免出现非连续的键
  • toArray():将Laravel集合转为普通PHP数组

方法二:批量处理所有列

如果要一次性处理多列,可以通过循环批量生成结果:

$results = Table::select('a','b','c','d')->groupBy('a','b','c','d')->get();
$targetColumns = ['a', 'b', 'c', 'd'];
$uniqueColumns = [];

foreach ($targetColumns as $col) {
    $uniqueColumns[$col] = $results->pluck($col)->unique()->values()->toArray();
}

// 使用时直接取对应键:$uniqueColumns['a']、$uniqueColumns['b']

性能优化建议

如果数据量较大,内存中去重的效率可能不如直接在数据库层面查询唯一值。可以单独对每列执行distinct查询:

$col_a = Table::distinct()->pluck('a')->toArray();
$col_b = Table::distinct()->pluck('b')->toArray();
$col_c = Table::distinct()->pluck('c')->toArray();
$col_d = Table::distinct()->pluck('d')->toArray();

这种方式让数据库直接返回唯一值,能减少内存占用,提升处理速度。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 08:55:21