2

When I do a find or fetch, the returned array of values contains string representations of all my columns regardless of the column's data type. This means instead of integer columns returning like:

array( 'field1' => 1 )

they end up as

array( 'field1' => '1' )

Is this expected behavior for CakePHP? Did I misconfigure something?

I thought about writing some code in the afterfind method of my models to call intval on the appropriate columns, but is that really the best solution? Does CakePHP have a better way of handling non-string columns?

2
  • Why do you have to use integer values? Commented Apr 13, 2012 at 0:33
  • I'm outputting the data as JSON for a web application that expects integers, not strings. Commented Apr 13, 2012 at 2:39

2 Answers 2

1

You can figure out what kind of field a field in the table your model is from the model property Model::_schema. Based on that you could type cast the values for your fields in the Model::afterFind() callback.

You can also manually check the fields you want to be integers but using _schema would allow you to automate it. You could do this as a behavior for example and attach it to every model that needs this functionality.

So simply iterate over the results and check for the fields you want to be integers and type cast them.

Sign up to request clarification or add additional context in comments.

2 Comments

Yeah, this seems like the best solution. I am just surprised that CakePHP doesn't do this automatically.
Because it would just add additional overhead that is in 99% never needed. I haven't had the case in all the years I do web applications that I had to type cast something for output. Btw: I just had an even better idea: Type cast the JSON result in javascript. This will move this work to the clients CPU :)
1

I noticed this too, and apparently it's the result of PDO casting everything to string. I submitted a ticket and hopefully there might be an automatic feature to coercion feature in the future.

Although the clients could convert the data, it's not very 'clean' especially when you might be providing the api to 3rd party developers.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.