Laravel Groupby并采取一些价值观
我正在使用Laravel 8.X和建筑REST API项目。 我被询问了。
我有一个桌子
ID | 名称 | 类型 | 颜色 |
---|---|---|---|
1 | 狗 | 动物 | 黑色 |
2 | 狗 | 动物 | 黄色 |
3 | 猫 | 动物 | 红色 |
4 | 猫 | 动物 | 白色 |
我想做这样的事情,
$ andy-&groupby('name'') - > get; get; ()
,希望得到结果,
$animals=[
{
name: "dog",
type: "animal",
colors: ["black", "yellow"]
},
{
name: "cat",
type: "animal",
colors: ["red", "white"]
}
]
有人帮我吗?
I am using laravel 8.x and building rest API project.
I am stuck with a query.
I have a table
id | name | type | color |
---|---|---|---|
1 | Dog | animal | black |
2 | Dog | animal | yellow |
3 | Cat | animal | red |
4 | Cat | animal | white |
I want to do something like that,
$animals->groupBy('name')->get()
and hope to get result like,
$animals=[
{
name: "dog",
type: "animal",
colors: ["black", "yellow"]
},
{
name: "cat",
type: "animal",
colors: ["red", "white"]
}
]
Anyone help me?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我将稍微改善Erik答案。
I will slightly improve the Erik answer.
我将使用 laravel maptogroups collection方法
带有输出:
I would use Laravel mapToGroups collection method
with output: