laravel 如何提取groupBy查询中各组的唯一值?

xqkwcwgp  于 2022-12-27  发布在  其他
关注(0)|答案(1)|浏览(136)

如果我有一个groupBy查询:

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]
5f0d552i

5f0d552i1#

    • 好了,现在我理解了你的问题,请看下面的解决方案:**在这种情况下,你不需要使用distinct,因为分组就可以了。
//Option 1 - Select only what you need
$query = Table::select('a', 'b', 'c', 'd')->get();

//Option 2 - if you need more data later
$query = Table::all();
        
$col_a = array_keys($query->groupby('a')->toArray());
$col_b = array_keys($query->groupby('b')->toArray());
$col_c = array_keys($query->groupby('c')->toArray());
$col_d = array_keys($query->groupby('d')->toArray());
    • 结果:**
$col_a = [a1, a2]
$col_b = [b1, b2, '']
$col_c = [c1, c2, c3]
$col_d = [d1, d2, d3 ,d4]

相关问题