Solved thread

This post is marked as solved. If you think the information contained on this thread must be part of the official documentation, please contribute submitting a pull request to its repository.

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.5k
Accepted
answer

You are looking for afterFetch

inside $model

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

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 : http://docs.phalconphp.com/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);
  }