如何在一个动作中填充2个模型

时间:2013-08-24 19:39:27

标签: php model yii

大家好, 我有2个模型用户和社区,我想通过使用模型用户的actionCreate将一些数据填充到模型社区中,但模型社区中没有保存任何内容,这是我的代码:

public function actionCreatec()
    {
            if($this->actionlogged()==0||$this->actionisadmin()==1)
            {
        $model=new Users;
                $model2=new Communities; 

        // Uncomment the following line if AJAX validation is needed
        $this->performAjaxValidation($model);
        if(isset($_POST['Users']))
        {

                    $model->attributes=$_POST['Users'];
                    $model2->idUser=$model->idUser;
                    $model2->admin=1;
                    $model2->save();
                    $model->userType='c';
                    $model->gender='n';
                    $model->firstName='null';
                    $model->lastName='null';
                    $model->birthDate='null';
                    $model->active=1;
                    $model->admin=0;

                    if(isset($_POST['profile'])==0)
                        $model->profilePhoto='default.jpg';
                    elseif(isset($_POST['profile'])==1)
                        $model->profilePhoto=CUploadedFile::getInstance($model,                'profilePhoto');

                    if($model->save()){
                        $this->actionfiledir();
                        if(isset($_POST['profile'])==1)
                            $model->profilePhoto->saveAs($this->actionphotodir()."/".$model->profilePhoto);
                        Yii::app()->session['userId']=$model->idUser;
                        $this->redirect(array('view','id'=>$model->idUser));
                    }
                }

        $this->render('createc',array(
            'model'=>$model,
        ));
            }
            else
                $this->redirect(array('site/index'));
    }

1 个答案:

答案 0 :(得分:1)

$ model2可能无法通过验证。你可以检查$ model2-> save();返回false,$ model2-> getErrors()(在保存方法后执行)以查看验证错误。

要跳过验证:

$model2->save(false);