如何将数据分组并获得数组中数据的所有值
示例
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(); < / p>
return response()->json(['status'=>'success','data'=>$data]);
答案 0 :(得分:1)
您可以在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);
}
答案 1 :(得分:0)
您可以在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 :(得分:0)
尝试
$data = DB::table('calendar')->orderBy('date','asc')->get()->groupBy('date')->toArray();