Saving Models with Relations Questions/Help

I am giving Yii a go, and started playing around with relations.

As good as the Guide is, it does not seem to answer the following questions (i might be wrong)

  1. Do relations need to be defined on both sides of a relation?

  2. Is relation Active record supposed to perform saves of the relations when you do a $model->save();

for example, using the data model from page 112 (minus tbl_ prefix) of the Yii guide, if the PostController is modified:


public function actionCreate()

	{

		$model=new Post;


		// Uncomment the following line if AJAX validation is needed

		// $this->performAjaxValidation($model);


		if(isset($_POST['Post']))

		{

			$model->attributes=$_POST['Post'];

			

			$model->create_time = new CDbExpression('NOW()');

			$model->author_id = '666';	// just for testing purposes		

			

			if($model->save())

				$this->redirect(array('view','id'=>$model->id));

		}


		$this->render('create',array(

			'model'=>$model,

		));

also the _form belonging to Post views is modified, removing the create time and author id and adding :


<div class="row">

<?php echo $form->dropDownList($model,'category', array('1' => 'One', '2' => 'Two', '3' => 'Three' )); ?>

	</div>

and the Post model modified to have the relation:




return array(

			'author'=>array(self::BELONGS_TO, 'User', 'author_id'),

			'category'=>array(self::MANY_MANY, 'Category',

				'post_category(post_id, category_id)'),

		);



When saving the post model, is it supposed to also create a row in post_category

populating post_id and category_id automagically? is the code complete enough for it to do that?

from what i have learnt:

  1. No, you dont have to specify relationship on both models, only in which you want to use relation by name you have.

  2. Yes, if relation is defined then its saved when main records is saved.

  1. Yes, but only if a Yii extension is used

/Tommy

Ok thanks guys, maybe a future release could have this feature built into the framework

making the Relations more complete. I dont really want to start adding extensions yet and

want to stick to the core framework as much as possible.

So ill go with manually performing the reklations for insert/updates and Ive found these links if anyones had the same question. It would be nice if the guide said that relations worked for selects only :).

http://www.yiiframework.com/wiki/19/how-to-use-a-single-form-to-collect-data-for-two-or-more-models/

http://www.yiiframework.com/wiki/291/update-two-model-with-one-view/

I’m currently working on an extension that is able to save relations… but it’s not that easy since you have to save many models at once, and every model can generate errors or need specific settings before/after saving. I don’t know any framework that supports this out of the box.