【问题标题】:How to make response json groupby and get all value of grouped如何制作响应json groupby并获取分组的所有值
【发布时间】:2019-03-23 22:20:11
【问题描述】:

如何获取数据分组并获取数组中数据的所有值

例子

id name    date       public
1  hi   2018-10-19    true
2  hai  2018-10-20    true
3  bye  2018-10-19    true

比我想要的响应 json 像

data:{
"2018-10-19": [
  {
     "name": "hi",
     "public": true
  },
  {
     "name": "bye",
     "public": true
  }
 ],
 "2018-10-20": [
  {
     "name": "hai",
     "public": true
  }
 ],
}

我试试这个

$data = DB::table('calendar')->select('date')->groupBy('date')->orderBy('date','asc')->get();

    return response()->json(['status'=>'success','data'=>$data]);

【问题讨论】:

    标签: sql json laravel laravel-5


    【解决方案1】:

    你可以在 laravel 集合中使用groupBy

    // retch the data from the databse as a collection.
    $data_collection_from_the_database = ....;
    
    // to group by date
    $grouped_collection = $data_collection_from_the_database->groupBy->date;
    
    // to get json
    $grouped_collection->toJson();
    

    【讨论】:

      【解决方案2】:

      试试这个

      $data = DB::table('calendar')->orderBy('date','asc')->get()->groupBy('date')->toArray();
      

      【讨论】:

        【解决方案3】:

        您可以在 laravel 查询中使用groupBy

        public function calendar($id)
        {
          #Calendar is a model name. 
          #data is relationship in Calendar model.
        
          $calendar = Calendar::whereHas('data', function ($query) use($id) {
            $query->where('id',$id);
          })->get()->groupBy(column_name_you_want_to_group_by);
            return response()->json([$calendar],200);
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-01-18
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-07-10
          • 1970-01-01
          相关资源
          最近更新 更多