I have a database table called miles, miles data looks like after fetch and return in Json.
"userMiles": [
{
"id": 278,
"gain_miles": 0.02,
"start_time": "2022-07-06T15:40:47+09:00",
"end_time": "2022-07-06T15:45:08+09:00",
},
{
"id": 279,
"gain_miles": 0.02,
"start_time": "2022-08-06T15:40:47+09:00",
"end_time": "2022-08-06T15:45:08+09:00",
},
]
I have written code to fetch data looks
$milesTable = TableRegistry::getTableLocator()->get( 'Miles' );
$query = $milesTable->find('all'));
try{
$userMiles = $this->paginate($query);
}
catch (NotFoundException $e){
$userMiles = [];
}
Now I'm trying to change this Json structure like below
"userMiles": [
{
"start_date": "06-July",
"miles":[
{
"id": 278,
"gain_miles": 0.02,
"start_time": "2022-07-06T15:40:47+09:00",
"end_time": "2022-07-06T15:45:08+09:00",
},
...
]
},
{
"start_date": "01-Mar",
"miles":[
{
"id": 281,
"gain_miles": 0.20,
"start_time": "2022-03-01T15:40:47+09:00",
"end_time": "2022-03-01T15:45:08+09:00",
},
...
]
},
]
For change Json Structure like above I have tried below codes , but don't know what is the procedure I will follow to get this output.
$query = $milesTable->find();
->select(["start_date" => "TO_CHAR(start_time,'DD-Mon')"])
->contain('Miles')
;
In `milesTable.php`
$this->hasMany('Miles',[
'foreignKey' => 'start_time',
'joinType' => 'LEFT',
]);
For this query getting error " "Unable to load Miles
association. Ensure foreign key in Miles
is selected."
My first query is Am I in right track ? Which procedure I can follow to get my desire output Json ?
I have tried by group by and order
$query = $milesTable
->find()
->select([
"start_date" => "TO_CHAR(start_time,'DD-Mon')",
"gain_miles",
"start_time",
"end_time",
])
->group(['start_date','id'])
->order(['start_time' => 'DESC'])
;
Output That I'm getting
"query": [
{
"start_date": "05-Jul",
"gain_miles": 400,
"start_time": "2022-07-05T14:14:23+06:00",
"end_time": "2022-07-06T14:14:23+06:00",
},
....
];
No if I use Collection
$collection = new Collection($query);
$miles = $collection->groupBy('start_date');
I'm getting my desire result, but problem is pagination, can I use pagination on collection $query data ? Or how can I implement pagination here ?