组Mysql在laravel中返回数据

问题描述 投票:0回答:3

我的MySQL返回值如下

{
    "BU_id": 1,
    "SE_id": 3815,
    "SE_name": "Director",
},
{
    "BU_id": 1,
    "SE_id": 3816,
    "SE_name": "Art Director",
},
{
    "BU_id": 2,
    "SE_id": 7032,
    "SE_name": "Regular",
},
{
    "BU_id": 2,
    "SE_id": 7033,
    "SE_name": "Member",
},

我希望我的返回数据按“BU_id”分组

{
    "BU_id": 1,
    {
      {
       "SE_id": 3815,
       "SE_name": "Director",
       },
       {
       "SE_id": 3816,
       "SE_name": "Art Director",
       },
    },
    "BU_id": 2,
    {
     {
     "SE_id": 7032,
     "SE_name": "Regular",
      },
      {
     "SE_id": 7033,
     "SE_name": "Member",
      },
    },
},

我尝试使用“groupBY('BU_id')”,但它完全删除了第二个数据,只显示了与BU_id对应的第一个数据

mysql laravel
3个回答
0
投票

您可以在select语句中使用group_concat()函数将结果与','连接。

就像是:

Select bu_id, group_concat(column_1) from table group by bu_id;

0
投票

这似乎是你需要的。

// If you get it from a model its already
$output = $service->keyBy('BU_id');
// If it is a normal array just collect it
$output = collect($service)->keyBy('BU_id');

资料来源:https://laravel.com/docs/5.5/collections#method-keyby


0
投票

使用Collection::groupBy方法按给定键对集合进行分组:

Model::all()->grouBy('BU_id');
© www.soinside.com 2019 - 2024. All rights reserved.