We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

castOnHydrate doesn't work when I select columns

Hello,

I put \Phalcon\Mvc\Model::setup(['castOnHydrate' => true]); in the bootstrap file (public/index.php) and when I specify some columns in the find it doesn't work :

// function to return json response
public function JSONBuilder($data, $code) {
    $response = new Response();

    $message = $this->getResponseDescription($code);

    $response->setHeader('Content-Type', 'application/json');
    $response->setStatusCode($code, $message);
    $response->setJsonContent($data);

    return $response;
}

// In my Action
$offices = Offices::find(array(
     "columns" => "id, code, description, email"
));

if (count($offices) < 1) {
    return $tools->JSONBuilder(array("error" => "Offices not found"), 404);
}

return $tools->JSONBuilder($offices->toArray(), 200);

So the cast is ignored and I'll get :

[
    {
        "id": "2",
        "code": "ANTB06",
        "description": "desc2",
        "email": "[email protected]"
    },
    {
        "id": "6",
        "code": "BATGN",
        "description": "desc6",
        "email": "[email protected]"
    }
    ...
]

But if I remove ->toArray() and I remove the columns key for the select it will works.

$offices = Offices::find();

if (count($offices) < 1) {
    return $tools->JSONBuilder(array("error" => "Offices not found"), 404);
}

return $tools->JSONBuilder($offices, 200);

I got my id property to integer :

[
    {
        "id": 2,
        "code": "ANTB06",
        "description": "desc2",
        "email": "[email protected]"
    },
    {
        "id": 6,
        "code": "BATGN",
        "description": "desc6",
        "email": "[email protected]"
    }
    ...
]

Can you tell me why ?

edited Feb '19

Hi @jonathan as you can see Resulset::toArray() doesn't have the same implementation than Model::toArray()

Good luck

Thanks for your answer. So you mean it's impossible to do what I want ?

Hi @jonathan as you can see Resulset::toArray() doesn't have the same implementation than Model::toArray()

Good luck



32.2k
Accepted
answer

now yes but you can overload the Resultset::toArray(); with something like this

class MyModel extends \Phalcon\Mvc\Model {
    public function toArray() {
        $result = [];
        foreach($this->_rows as $row) {
            $result[] = $row->toArray();
        }
        return $result;
    }
}

Good luck