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

Save data in related models

Hi i have problem in saving data when my models are related. i have to tables: admin and admin_token

for admin:

    public $id;
    public $username;
    public $password;
    public $logged_in;
    public function initialize()
    {
        $this->setSource("admin");
        $this->hasMany(
            'id',
            'App\\Models\\AdminTokens',
            'admin_id',
            [
                'alias' => 'Tokens',
            ]
        );
    }

and for admin_token:

    public $id;
    public $admin_id;
    public $is_revoked;
    public function initialize()
    {
        $this->setSource("admin_tokens");
        $this->belongsTo(
            'admin_id',
            'App\\Models\\Admin',
            'id',
            [
                "alias" => "Admin",
            ]
        );
    }

now in controller something like blow wont work:

    $admin = Admin::findFirstByUsername($username);
    foreach( $admin->tokens as $token ) {
            $token->is_revoked = 1;
    }
    $tokens = [];
    $tokens[0] = new AdminTokens();
    $tokens[0]->admin_id = $admin->id;
    $tokens[0]->is_revoked = 0;
    $admin->tokens = $tokens;

    $admin->logged_in = 1;
    $admin->save()

is there any idea why this method not only update token and set them to 1 but also it does not save any token in admin_tokens table?



47.7k

Have you tried saving your token before assigning it to admin->tokens ?

I think im pretty sure that the problem is that you first access it with $admin->tokens not sure though what exactly you update there and how you want to do it beacause you are not really saving those tokens. Well you shouldn't really access magic property when they are used for relations and then update beacause then when setting relation - this property is not longer magic and __set won't be fired causing not updating related models. Best is to add method getTokens:

public function getTokens()
{
    return $this->getRelated('Tokens');
}