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

Why doesn't the toArray() on models use the model's getter methods?

I have a Phalcon\Mvc\Model that has various getter properties like getMetadata(). Some of the values in the database are JSON types, such as the metadata column. The corresponding properties on the models are strings (JSON strings, specifically). I have getters on the model that convert the JSON strings to arrays via json_decode() Those work fine in cases where I call them directly.

However, whenever I call the toArray() method on the model, it returns an array with metadata as the JSON string instead of the converted associative array, completely ignoring my getter.

Is there a way to make toArray() use the getters? If not, what would be the recommended way of getting the object as an array, using the getters I've defined on the model? Phalcon uses the setters whenever I set values, so I'm surprised it doesn't naturally use the getters.

edited Jun '20

Hi, I faced the same issue with toArray. I think for now the better choice you have to deal with this, is redefining the toArraymethod in your Model like this:

MyClass extends Model
    protected $json_property;

    public function getJsonProperty(){}

    public function toArray($columns = null): array{
        $result = parent::toArray($colums);
        if (isset($result['json_property'])){
            $resut['json_property'] = $this->getJsonProperty();
        return $result;

I hope this solution might help.

The other solution you might have is to create a new MyModel, completely rewrite toArray in that model (Converting z├ęphir to PHP is easy), and make the appropriate changes to use Getter whenever it's needed. Once done, you could also suggest a solution to the repo to have everybody enjoy the fix. :-)