2

I recently was introduced into the Yii Framework and am presently developing a web application system for my company. However I noticed that when creating the model in order to give the connection to the respective table, it only allows to choose one relation at a time. However I need to connect two separate tables from the same database with a single form.

Any ideas on how this could be accomplished?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Yoosuf
  • 882
  • 7
  • 33
  • 52

1 Answers1

5

Inside the models you can see the below function,

    /**
 * @return array relational rules.
 */
public function relations()
{
    return array(

    );
}

in this you can add relations. like

'user' => array(self::BELONGS_TO, 'User', 'user_id'),
'comments' => array(self::HAS_MANY, 'Comments', 'blog_post_id'),

etc.,

If your database engine is in Innodb and tables have foreign key relations , then the relations will be automatically generated while creating the models.

For more info read this

you can use any number of relations.

=============================================

And after second reading, I think you were asking about getting objects of two models into one form? for that you can generate objects of each model in controller and pass those objects to view via render or renderPartial function

e.g.,

$this->render('admin',array(
            'model'=>$model,
                    'model2'=>$model2,
        ));

and inside the view use model and model2 for respective fields

<?php $form=$this->beginWidget('CActiveForm', array(
    'id'=>'sample-form',
    'enableAjaxValidation'=>false,
)); ?>

.....

        <?php echo $form->labelEx($model,'column'); ?>
        <?php echo $form->textField($model,'column'); ?>
        <?php echo $form->error($model,'column'); ?>

        <?php echo $form->labelEx($model2,'column'); ?>
        <?php echo $form->textField($model2,'column'); ?>
        <?php echo $form->error($model2,'column'); ?>


....

inside the controller function use something like below(say for saving data)

$model->attributes=$_POST['ModelOnesName'];
$valid  =   $model->validate();
$model2->attributes =   $_POST['ModelTwosName'];
$valid  =   $model2->validate() && $valid; //if need validation checks
if($valid)
{
   $model->save();
   $model2->save();
}
arun
  • 3,667
  • 3
  • 29
  • 54