Welcome Guest, Not a member yet? Register   Sign In
Entity object attribute update problem
#1

(This post was last modified: 01-24-2023, 01:09 AM by ruslan.)

Currently if i have JSON column `data` in the database and use Entity's i can not do this (i want to update a `role` property of `data` object of `user` entity):

PHP Code:
$user->data->role "user";
$userModel->save($user); 

It says there is nothing to update
I have to do this:


PHP Code:
$data $user->data;
$data->role "user";
$user->data $data;
$userModel->save($user); 

Is there a better way to say Entity that some attribute has been updated?
Reply
#2

Did you create a getUser and setUser methods in your Entity Class?
What did you Try? What did you Get? What did you Expect?

Joined CodeIgniter Community 2009.  ( Skype: insitfx )
Reply
#3

(01-24-2023, 01:20 AM)InsiteFX Wrote: Did you create a getUser and setUser methods in your Entity Class?

You mean setData and getData?
User class extends Entity class

No. How will that help?
Reply
#4

See https://codeigniter.com/user_guide/model...on-casting
Reply
#5

(01-24-2023, 01:39 AM)kenjis Wrote: See https://codeigniter.com/user_guide/model...on-casting

yes, the same technique in the docs

PHP Code:
$user    $userModel->find(15);
$options $user->options;

$options['foo'] = 'bar';

$user->options $options;
$userModel->save($user); 

ok
Reply
#6

PHP Code:
class Jsonable
{
    protected Entity $entity;

    protected string $attribute;

    protected object $data;

    /**
    * @param Entity $entity
    * @param string $attribute
    * @param string $data
    */
    public function __construct(Entity $entitystring $attributestring $data)
    {
        $this->entity $entity;
        $this->attribute $attribute;
        $this->data json_decode($data);
    }

    public function __get($name)
    {
        return $this->data->{$name};
    }

    public function __set($name$value)
    {
        $this->data->{$name} = $value;
        $this->entity->{$this->attribute} = json_encode($this->data);
    }


PHP Code:
class MyEntity extends Entity
{
    protected $attributes = [
        'data' => '{"role":"admin", "ban":"y"}',
    ];

    protected $original = [
        'data' => '{"role":"admin", "ban":"y"}',
    ];

    public function getData()
    {
        return new Jsonable($this'data'$this->attributes['data']);
    }
}

$e = new MyEntity();
$e->toRawArray(); // array ('data' => '{"role":"admin", "ban":"y"}',)

$e->data->role "user";
$e->data->ban "n";

$e->toRawArray(); // array ('data' => '{"role":"user","ban":"n"}',) 
Reply
#7

(01-24-2023, 11:28 PM)iRedds Wrote:
PHP Code:
class Jsonable 

Thank you!
Nice hack
Although only works with the first level properties of the json object
Reply




Theme © iAndrew 2016 - Forum software by © MyBB