laravel - How can I group by specific field in Laravel?
问题描述
This is 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 }
And I am going to get this result by using Laravel Eloquent ORM.
{ "author" : "Homer", "books" : [ "The Odyssey", "Iliad" ] }
{ "author" : "Dante", "books" : [ "The Banquet", "Divine Comedy", "Eclogues"
] }
How can I do? Please help me.
解决方案
$books
如果是实例,请尝试此代码Collection
$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
收集数据
推荐阅读
- android - Ionic 4 与 Ionic 3 中的后台工作人员
- c# - BoundedChannel、BufferBlock 还是其他?
- react-native - reducer 返回状态,但未调用组件 getDerivedStateFromProps
- c# - 改源后UWP播放MediaElement
- sql - 在 SQL Server 2016 中使用 JSON 进行字符串聚合
- angular - 在 angular2 中使用 HttpParams 的 Http 获取返回 404 错误
- python - 我可以使用标记化的输入文件和高棉语的自定义词汇文件从头开始预训练 BERT 模型吗
- python - urllib.error.HTTPError:HTTP 错误 404:找不到可以在浏览器中打开的链接
- python - 迁移学习 TypeError:“模块”对象不可调用
- sql-server - 获取 SQL Server 中表类型参数的创建行