【问题标题】:Laravel groupBy and pluck some valuesLaravel groupBy 并提取一些值
【发布时间】:2022-07-08 04:19:09
【问题描述】:

我正在使用 laravel 8.x 并构建 rest API 项目。 我遇到了一个问题。

我有一张桌子

id name type color
1 Dog animal black
2 Dog animal yellow
3 Cat animal red
4 Cat animal white

我想做这样的事情,

$animals->groupBy('name')->get()

并希望得到类似的结果,

$animals=[
          {
           name: "dog",
           type: "animal",
           colors: ["black", "yellow"]
          },
          {
           name: "cat",
           type: "animal",
           colors: ["red", "white"]
          }
         ]

有人帮帮我吗?

【问题讨论】:

    标签: php laravel eloquent laravel-8


    【解决方案1】:

    我会使用Laravel mapToGroups collection method

    $data = Animal::get();
    
    $animals = collect($data)->mapToGroups(function ($item) {
                return [$item['name'] => $item];
            })->map(function ($itemGoup, $name) {
                return [
                    'name' => $name,
                    'type' => data_get($itemGoup, '0.type'),
                    'colors' => collect($itemGoup)->pluck('color')->unique()->values()->toArray(),
                ];
            })->values()->toArray();
    
    

    带输出:

    [
        {
            "name": "Dog",
            "type": "animal",
            "colors": ["black", "yellow"]
        },
        {
            "name": "Cat",
            "type": "animal",
            "colors": ["red", "white"]
        }
    ]
    

    【讨论】:

      【解决方案2】:

      我会稍微改进 Erik 的答案。

              $data = Animals::get();
      
              $animals = collect($data)->groupBy('name')->map(function($item) {
                  return [
                      'name' => $item[0]['name'], // the name always the same
                      'type' => $item[0]['type'], // if the type not change (as the name)
                      'colors' => $item->pluck('color')->unique()->toArray(),
                  ];
              })->values()->toArray();
      

      【讨论】:

        猜你喜欢
        • 2018-12-09
        • 1970-01-01
        • 2020-12-19
        • 1970-01-01
        • 1970-01-01
        • 2022-01-26
        • 1970-01-01
        • 2021-05-14
        • 2020-04-17
        相关资源
        最近更新 更多