gpt4 book ai didi

laravel - 如何提取每组 groupBy 查询的唯一值?

转载 作者:行者123 更新时间:2023-12-05 04:19:11 32 4
gpt4 key购买 nike

如果我使用 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]

最佳答案

好的,现在我了解您的问题,请参阅以下解决方案:在这种情况下您不需要使用 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]

分组依据::

The MySQL GROUP BY Statementgroups rows that have the same values into summary rows, like "find the number of customers in each country". https://www.w3schools.com/mysql/mysql_groupby.asp

关于laravel - 如何提取每组 groupBy 查询的唯一值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74912723/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com