We are moving our forum in GitHub Discussions. For questions about Phalcon v3/v4 you can visit here and for Phalcon v5 here.

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 do i unserialize and serialize model fileds when save and read models?

I want to store a serialized value into a model,but i don not know how to do that.



40.7k
Accepted
answer
edited Mar '14

This way:

class Robots extends \Phalcon\Mvc\Model
{
    public function beforeUpdate()
    {
        $this->my_parameters = serialize($this->my_parameters);
    }

    public function afterFetch()
    {
        $this->my_parameters = unserialize($this->my_parameters);
    }    
} 
class Test extends \Phalcon\Mvc\Controller
{
    public function testAction()
    {
        this->view->disable(); //disable views to see output in test controller, test action http://localhost/test/test
        echo "<pre>";

        $robot = Robots::findFirst("id=1");
        print_r($robot->my_parameters);
        // table field my_parameters is automaticaly unserialized in model method afterFetch()
        // return array('color'=>'red', 'material'=>'steel');

        $robot->my_parameter['size']=220;

        $robot->update();
        // in table field my_parameters will be serilized automaticaly in model method beforeUpdate()

        $robot2 = Robots::findFirst(1);
        print_r($robot2->my_parameters);
    }
}

http://localhost/test/test

Array
(
    [color] => red
    [material] => steel
)

Array
(
    [color] => red
    [material] => steel
    [size] => 220
)


4.3k

thanks. It works. ^ _ ^ In this way, i don't need use serialize/unserialize func in getter/setter func. thanks a lot.