Eric
Eric

Reputation: 4395

Yii PHP - JSON encoding active records turns ints and booleans into strings

In my database I have a friends table that has the following structure:

I have an active record query that looks like this:

$friends = Friend::model()->findAll('user_a=:userId AND accepted IS true', array(':userId' => $this->user->id));
$this->sendResponse(200, CJSON::encode($friends), 'application/json');

And I get back the following API response:

[{"id":"2","user_a":"14","user_b":"3","accepted":"1"}]

CJSON::encode seems to be turning everything into a string, why is this? Is there a way to return the ints as numbers and tinyints as booleans?

Thanks,

Eric

Upvotes: 0

Views: 475

Answers (1)

Andrii Mishchenko
Andrii Mishchenko

Reputation: 2694

CJSON::encode() does not turn variables to strings - but findAll() does. If you dump $friends models attributes you will see it. You can do something like this to deal with it:

protected function afterFind()
{
    $this->id = (int) $this->id;
    $this->user_a = (int) $this->user_a;
    // etc
    parent::afterFind();
}

Upvotes: 2

Related Questions