Code Commander
Code Commander

Reputation: 17290

How can I retrieve integer values for integer columns in CakePHP?

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?

Upvotes: 2

Views: 1002

Answers (2)

Jamescowhen
Jamescowhen

Reputation: 95

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.

Upvotes: 1

floriank
floriank

Reputation: 25698

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.

Upvotes: 1

Related Questions