簡體   English   中英

Laravel groupBy 並提取一些值

[英]Laravel groupBy and pluck some values

我正在使用 laravel 8.x 並構建 rest API 項目。 我被一個查詢困住了。

我有一張桌子

ID 姓名 類型 顏色
1 動物 黑色的
2 動物 黃色
3 動物 紅色的
4 動物 白色的

我想做這樣的事情,

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

並希望得到類似的結果,

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

有人幫我嗎?

我會稍微改進 Erik 的答案。

        $animals = Animals::all()->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();

我會使用Laravel mapToGroups 收集方法

$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"]
    }
]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM