Insert new model/record with a BELONGS_TO

Hi All

I have this user which belongs to a company (so the user table has a company_id column which is required), so I have a rule


'company'       => array(self::BELONGS_TO, 'Company', 'company_id'),

Furthermore, company has a rule


'users' => array(self::HAS_MANY, 'User', 'company_id'),

So when I create a new model like




     $model = new User();

     $model->attributes=$_POST['User']; // doesn't contain company_id

     $company = Company::model()->find( 'name=:name', array( ':name'=> $strCompany) ) ;

     $model->company = $company ;

     .... $model->save() ....



When I execute this I get the error company_id is not defined. When I remove company_id from the required rule I get a more serious error, something like

However, when I replace


$model->company = $company ;

with


$model->company_id = $company->id ;

it works. Shouldn’t the first approach work too ? If so, what might go wrong ?

If more info is needed please ask!

cheers

Luca

UPDATE: one more thing, the foreign-key I have looks like


$this->addForeignKey('fk_user_company_id', 'tbl_user', 'company_id', 'tbl_company', 'id', 'NO ACTION', 'NO ACTION') ;

UPDATE2: I made some changes to this post

The Basic Yii doesnt support this behavior.

But there is an extension for that :)

The extension is CAdvancedBehavior you can download it there: http://www.yiiframework.com/extension/cadvancedarbehavior/

The only thing that you have to do is to add this Behavior to your Model!

Thanks a lot. The plugin you mention is for MAN_MANY only, but it helped me to create this one:

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

cheers