问题
Situation
Using cake 3.2.4
and the plugin Crud 4.2
for the purpose of producing an API feed
What code did I use at first?
$this->Crud->on('beforePaginate', function(Event $event) use ($conditions) {
$this->paginate['conditions'] = $conditions;
$this->paginate['limit'] = 100;
$this->paginate['fields'] = [
'id', 'title',
'start_date',
'end_date',
'revenue',
'total_costs', 'collections'
];
});
What am I getting as json feed?
"success": true,
"data": [
{
"id": 789,
"title": "9143 - Asia Summit",
"start_date": "2016-03-02T09:00:00+0800",
"end_date": "2016-03-04T18:45:00+0800",
"revenue": 1000000.00,
"total_costs": 0,
"collections": 50000.00
},
{
"id": 15,
"title": "9144 - 10th Exhibition",
"start_date": "2016-03-21T09:00:00+0800",
"end_date": "2016-03-23T17:00:00+0800",
"revenue": 2000000.00,
"total_costs": 0,
"collections": 50000.00
}]}
What did I then do?
I wanted to return as aliases so I did the following
$this->Crud->on('beforePaginate', function(Event $event) use ($conditions) {
$this->paginate['conditions'] = $conditions;
$this->paginate['limit'] = 100;
$this->paginate['fields'] = [
'id', 'title',
'start' => 'start_date',
'end' => 'end_date',
'revenue',
'costs' => 'total_costs', 'collections'
];
});
What did I now get?
{
"success": true,
"data": [
{
"id": 789,
"title": "9143 - Asia Summit",
"start": "2016-03-02 09:00:00",
"end": "2016-03-04 18:45:00",
"revenue": 1000000.00,
"costs": "0.00",
"collections": 50000.00
},
{
"id": 15,
"title": "9144 - 10th Exhibition",
"start": "2016-03-21 09:00:00",
"end": "2016-03-23 17:00:00",
"revenue": 2000000.00,
"costs": "0.00",
"collections": 50000.00
},
So what's wrong?
I get the aliases I wanted, but then the costs has now become a string.
The datetime no longer shows the timezone.
How do I force the fields of the objects in the json feed to be of a certain type whilst keeping the aliases?
回答1:
Realise that in 3.2 you can use addDefaultTypes to affect the query directly
See Cakephp-3.x: How to change the data type of a selected alias?
Realise that you can access the query from $event when using Crud
See http://crud-view.readthedocs.org/en/latest/basic-usage.html?highlight=query#providing-associations-to-be-displayed
Use the types datetime, and decimal
Put it altogther and you get:
$this->Crud->on('beforePaginate', function(Event $event) use ($conditions) {
$this->paginate['conditions'] = $conditions;
$this->paginate['limit'] = 100;
$this->paginate['fields'] = [
'id', 'title',
'start' => 'start_date',
'end' => 'end_date',
'revenue',
'costs' => 'total_costs', 'collections'
];
$paginationQuery = $event->subject()->query;
$paginationQuery
->selectTypeMap()
->addDefaults([
'start' => 'datetime',
'end' => 'datetime',
'costs' => 'decimal'
]);
});
来源:https://stackoverflow.com/questions/35972918/how-to-set-aliases-and-then-still-affect-the-return-type-for-queries-in-json-for