使用具有不同特征的GroupBy进行Laravel查询 [英] Laravel Query using GroupBy with distinct traits

查看:97
本文介绍了使用具有不同特征的GroupBy进行Laravel查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

试图弄清楚如何显示具有这样数据的数据库的结果...

Trying to figure out how I can display results for a database that has data like this...

如果数据是这样存储的...

If the data is stored like this...

 Style              Color

  1. 经典帽子-红色
  2. 经典帽子-蓝色
  3. 经典帽子-黄色
  4. 时髦的帽子-红色
  5. 时髦的帽子-蓝色
  6. 无尘帽-黑色

如果我想显示这样的数据

If I want to show the data like this

颜色:红色,蓝色,黄色

Colors: Red, Blue, Yellow

颜色:红色,蓝色

颜色:黑色

我无法弄清楚如何同时分组以及显示分组中的不同特征.我看到了一些示例,这些示例显示了如何显示每个不同的计数,但没有显示如何显示分组记录的唯一特征值.

I cant figure out how to simultaneously group by as well as show the distinct traits within the group. I see examples of how to show the count of each distinct, but not how to display unique trait values for grouped records.

推荐答案

您可以从模式中获取正常的集合,即. Styles::all().然后在集合上使用groupBy函数.

You can just fetch a normal collection from the modal, ie. Styles::all(). Then use the groupBy function on the collection.

// Sample data as per database query
$data = collect([
    ['style' => 'classy hat', 'color' => 'red'],
    ['style' => 'classy hat', 'color' => 'orange'],
    ['style' => 'classy hat', 'color' => 'green'],
    ['style' => 'stylish hat', 'color' => 'blue'],
    ['style' => 'stylish hat', 'color' => 'orange'],
]);

$styles = $data->groupBy('style');

foreach ($styles as $style => $colors) {
    echo "<h1>" . $style . "</h1>";
    echo implode(', ', $colors->pluck('color')->toArray());
}

那会给你

经典帽子

红色,橙色,绿色

时髦的帽子

蓝色,橙色

或者,您可以构建所需的整个数组:

Alternatively you can build the whole array you need:

$styles = $data->groupBy('style')
    ->map(function ($styles) {
        return $styles->pluck('color');
    });

print_r($styles->toArray());

Array
(
[classy hat] => Array
    (
        [0] => red
        [1] => orange
        [2] => green
    )

[stylish hat] => Array
    (
        [0] => blue
        [1] => orange
    )

更新以打印

foreach ($styles->toArray() as $style => $colors) {
    echo "<h1>" . $style . "</h1>";
    echo implode(', ', $colors) . "<br />";
}

更新刀片视图

@foreach ($styles->toArray() as $style => $colors)
    <h1>{{ $style }}</h1>
    @foreach ($colors as $color)
        {{ $color }},
    @endforeach
    <!-- OR -->
    {{ implode(', ', $colors) }} 
@endforeach

这篇关于使用具有不同特征的GroupBy进行Laravel查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆