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 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.8k
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 https://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);
    }
}

https://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.