我正在做一个项目。我想在一个相同的形式保存2个模型。我尝试过这样:在QController.php中使用actionCreate
public function actionCreate()
{
    $model=new Question;
    $test=new Answer;
    if(isset($_POST['Question']) && ($_POST['Answer']))
    {
        $model->attributes=$_POST['Question'];
        $model->question=CUploadedFile::getInstance($model,'question');
        $test->attributes=$_POST['Answer'];
        $valid=$model->validate();
        $valid=$test->validate() && $valid;
        if($valid){
            $model->save(false);
            $test->save(false);
            $model->question->saveAs(Yii::app()->basePath . '/../images/questions/' . $model->question.'');
            $this->redirect(array('view','id'=>$model->id_question));
        }
     }
   $this->render('create',array(
         'model'=>$model,
         'test'=>$test,
   ));
}然后,在我的Q/_form.php中
<?php $form=$this->beginWidget('bootstrap.widgets.TbActiveForm',array(
'id'=>'question-form',
'enableAjaxValidation'=>false,
)); ?>
<?php $answerModel = new Answer; ?>
<p class="help-block">Fields with <span class="required">*</span> are required.</p>
<?php echo $form->errorSummary($model, $answerModel); ?>
<?php echo $form->fileFieldRow($model,'question',array('class'=>'span5','maxlength'=>50)); ?>
<?php echo $form->textFieldRow($answerModel,'optionA',array('class'=>'span5','maxlength'=>100)); ?>
//rest of codes
<?php $this->endWidget(); ?>我已经尝试过了,但仍然没有保存数据。我怎么做才能修复它呢?谢谢你的回答
发布于 2014-08-06 23:34:25
您应该先验证数据,然后再保存数据:
$model->attributes=$_POST['Question'];
$test->attributes=$_POST['Answer'];
$valid = $model->validate();
$valid = $location->validate() && $valid;
if ($valid) {
    // use false parameter to disable validation
    $model->save(false);
    $test->save(false);
    // redirect
}对于事务:
$model->attributes=$_POST['Question'];
$test->attributes=$_POST['Answer'];
$valid = $model->validate();
$valid = $location->validate() && $valid;
if ($valid) {
    $dbTransaction = Yii::app()->db->beginTransaction();
    try {
        // use false parameter to disable validation
        $model->save(false);
        $test->save(false);
        $dbTransaction->commit();
        // redirect here
    } catch (Exception $e) {
        $dbTransaction->rollBack();
        // save/process error
    } 
 }https://stackoverflow.com/questions/25164084
复制相似问题