Hello!
I’m trying to set the value of a relational attribute using an object already created. Is it possible to accomplish this?
For example:
I have the User model that has by aggregation a Lang model as the user configured language.
class User extends ActiveRecord
{
...
public function relations()
{
return array(
'lang' => array(self::BELONGS_TO, 'Lang', 'lang_id')
);
}
...
}
class Lang extends ActiveRecord
{
...
public function relations()
{
return array(
'users' => array(self::HAS_MANY, 'User', 'lang_id'),
);
}
...
}
The question is, can I assing directly an object to the related attribute to change the parent model?
For example:
$user = User::model()->findByPk(1);
$newlang = Lang::model()->findByPk(5);
echo $user->lang->id; //prints 2
$user->lang = $newlang;
$user->save();
$user = User::model()->findByPk(1); //Reload
echo $user->lang->id;
My problem is that the last code line prints "2", not "5".
Thanks!