如何在Laravel中按特定领域分组?

时间:2018-12-19 19:07:04

标签: laravel

这是Book table

{ "_id" : 8751, "title" : "The Banquet", "author" : "Dante", "copies" : 2 }
{ "_id" : 8752, "title" : "Divine Comedy", "author" : "Dante", "copies" : 1 
}
{ "_id" : 8645, "title" : "Eclogues", "author" : "Dante", "copies" : 2 }
{ "_id" : 7000, "title" : "The Odyssey", "author" : "Homer", "copies" : 10 }
{ "_id" : 7020, "title" : "Iliad", "author" : "Homer", "copies" : 10 }

我将通过使用Laravel Eloquent ORM获得此结果。

{ "author" : "Homer", "books" : [ "The Odyssey", "Iliad" ] }
{ "author" : "Dante", "books" : [ "The Banquet", "Divine Comedy", "Eclogues" 
] }

我该怎么办? 请帮助我。

1 个答案:

答案 0 :(得分:1)

如果$booksCollection的实例,请尝试以下代码

$collection = collect([
    [
        "title" => "The Banquet",
        "author" => "Dante",
        "copies" => 2
    ],
    [
        "title" => "Divine Comedy",
        "author" => "Dante",
        "copies" => 1
    ],
    [
        "title" => "The Odyssey",
        "author" => "Homer",
        "copies" => 10
    ]
]);

$result = [];

foreach($collection->groupBy('author') as $author => $books) {
    $data['author'] = $author;
    $data['books'] = $books->pluck('title')->all();
    $result[] = $data;
}
dd(json_encode($result));

结果是

[{"author":"Dante","books":["The Banquet","Divine Comedy"]},{"author":"Homer","books":["The Odyssey"]}]

感谢@xyingsoft的收集数据