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


how to fill 2 models in one action

大家好,我有两个模型用户和社区,我想通过使用模型用户的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'));
    }

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

跳过验证:

$model2->save(false);