In cake php I can grab a model's fields by using the find() method. What if I wish to apply a transformation function to the fields? Is there a way to directly accomplish this task?
Suppose I have a model called RaceTime
with the fields racerId
and timeMillis
RaceTime
+------------+
| Field |
+---------开发者_如何学运维---+
| id |
| racerId |
| timeMillis |
+------------+
timeMillis is an int specifying how long the race took in milliseconds. Obviously saying a race took 15651 milliseconds isn't very useful to a human reader, and I would wish to convert this to a human readable format.
Is there a way to accomplish this directly in find()?
Or is the only option to loop through the results after find() finishes?
What you want is possible using Virtual Fields.
Edit with an example:
var $virtualFields = array(
'timeMillisHR' => 'FROM_UNIXTIME(Field.timeMillis)'
);
Assuming you only wish to convert timeMillis into seconds, you can use 'fields'=>array('timeMillis/1000', 'other_fields') where 'other_fields' represents the other fields you wish to retrieve as part of your query. If it is more complicated than just simple mathematical operations and other SQL functions, then the answer is No.
If it is a common enough transformation in your project, and you can't findoa suitable method in either the TimeHelper of the NumberHelper, then you can easily write your own helper.
You pretty much have to loop through every instance you wish to transform.
精彩评论