Laravel集合返回数组

时间:2020-09-12 09:39:13

标签: php laravel collections

所以我有这张桌子

|id|    price    |  start_time |
--------------------------------
|1 |    45000.00 |  04:45:00   |
|1 |    45000.00 |  07:00:00   |
|2 |    40000.00 |  01:20:00   |

我想制作一个返回json这样的集合

{
   id: 1
   price: 45000.00
   start_time: [
        04:45:00, 07:00:00
    ]
},
{
   id: 2
   price: 40000.00
   start_time: [
        01:20:00
    ]
}

我花了很多时间来解决它,但我做不到

请先谢谢我帮忙

1 个答案:

答案 0 :(得分:1)

使用map()

 $laravelCollcetion->map(function($row){
       return $row['start_time'] = [$row['start_time']]
  })

return $laravelCollcetion;

参考链接https://laravel.com/docs/7.x/collections#extending-collections


对于您的数据库实例,您可以这样做

 $data = \DB::table('schedules')
        ->select(\DB::raw('id, price,GROUP_CONCAT(start_time) as start_time'))
        ->groupBy('id')
        ->get();

return $data;