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

How I run code after a model has retrieved from the database?

Hello,

I have a database table which has 1 field that stores JSON. In my model, the variable which is turned into json is an array. Using the beforeSave method, I json_encode the array for storage in the database.

What I need to do is when an existing record is fetched from the database, automatically json_decode it back into an array.

For example:


$model->myValue = [
    'array1' => [
        'key1' => 'value1',
        'key2' => 'value2'
    ]
];

$model->save(); // This triggers beforeSave, json encoding the array.

// Now, when I retrieve a value, it should be automatically decoded:

$model = MyModel::findFirst();

echo $model->myValue['array']['key1']; // Outputs value1

This attempt to decode the value of the variable would of course only need to run when fetching an existing record, not always when an object of that model is instantiated (example: new MyModel()).

So, does anyone know how I can accomplish this? Thanks



6.9k
Accepted
answer

You are looking for afterFetch

inside $model

    public function afterFetch()
    {
        $this->myValue = json_decode($this->myValue);
    }


12.6k

Oh, that does sounds like what I need, thanks!

The docs could really use some updating... I didn't even notice that. I was looking at : https://docs.phalcon.io/en/latest/reference/models.html#events-and-events-manager

The events there are much easier to find!

You are looking for afterFetch

inside $model

   public function afterFetch()
   {
       $this->myValue = json_decode($this->myValue);
  }