Answer the question
In order to leave comments, you need to log in
How in PHP, preferably compatible with Yii2 ActiveDataProvider, to select data from a table in order to group them by date in JSON?
This is what the query looks like without "grouping":
$query = $query->orderBy(['dt' => SORT_DESC, 'id' => SORT_DESC]);
return new ActiveDataProvider([
'query' => $query,
'pagination' => [
...
]
]);
{
"items": [
{
"id": "5",
"dt": "2017-01-10 07:56",
...
},
{
"id": "4",
"dt": "2017-01-10 07:55",
...
},
{
"id": "3",
"dt": "2017-01-09 13:52",
...
},
...
]
}
{
"items": [
"2017-01-10": [
{
"id": "5",
"dt": "2017-01-10 07:56",
...
},
{
"id": "4",
"dt": "2017-01-10 07:55",
...
}
],
"2017-01-09": [
{
"id": "3",
"dt": "2017-01-09 13:52",
...
}
]
...
]
}
$query = $query->orderBy(['dt' => SORT_DESC, 'id' => SORT_DESC]);
$rawArr = $query->all();
Answer the question
In order to leave comments, you need to log in
This will be needed later in the front-end.
You cannot get the desired result through group by.
Usually this is done after receiving all the records of interest, something like:
$byDate = ArrayHelper::map($dataProvider->getModels(), 'dt', function($data) { return $data; });
In the simplest version, you can do something like this:
$query = $query->orderBy(['dt' => SORT_DESC, 'id' => SORT_DESC]);
$dataProvider = new ActiveDataProvider([
'query' => $query,
'pagination' => [
.....
]
]);
$dataProvider->models = \yii\helpers\ArrayHelper::index($dataProvider->models, null, 'dt');
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question