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

Not update ForeignKey value

Hello!

There are 2 tables:

Users (id, login, pass, role_id)
Roles (id, name, description)

Each user has a role (role_id link with table Roles via ForeignKey). In Roles model written:

$this->belongsTo('role_id', __NAMESPACE__ . '\Roles', 'id', array(
        'alias' => 'Role'
));

When I try to update user's role I have a problem: always write the same role, which stand on the first place in Roles table.

I try update user's role with 2 ways:

$user->role_id = 4; // not works
$user->Role->id = 4; // (WARNING) it works, because when I update ID in Roles, this implace update in Users table

Record with ID 4 there is in Roles table.

In Phalcon there is same bug with null value in ForeignKey field (one, two, three, four)

My Phalcon version is 1.3.2.

Sorry for my bad English.



98.9k
Accepted
answer
edited Aug '14

You have to update the role_id itself or update the role using an instance of Roles:

$user->role_id = 4; 
if ($user->save() == false) {
    foreach ($user->getMessages() as $message) {
        echo $message;
    }
}
$role = Roles::findFirstById(4);
$user->role = $role; 
if ($user->save() == false) {
    foreach ($user->getMessages() as $message) {
        echo $message;
    }
}


686

Thanks! It works!