Update related attribute by objects

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!

At least this should work




$user->lang_id = $newlang->id;



(BTW I think the answer to your question is: no, not supported)

/Tommy

IMO the answer to your question is, not supported in Yii by default but you can take a look at these extensions and will give you that functionality and more:

http://www.yiiframework.com/extension/eadvancedarbehavior/

and

http://www.yiiframework.com/extension/cadvancedarbehavior/

Ohh… this was just what I wanted to avoid.

Because doing this… I’m thinking in term of relational model instead of object oriented model, then we don’t really need a lang_id attribute, we only need an object in User.

I’m going to check the extensions that you recommended Asgaroth to see how I go.

Thanks for answer!

Regards!

I am considering to add your requirement to this extention I wrote:

http://www.yiiframework.com/extension/esaverelatedbehavior/