正在需要的时候发现了这个大牛的博文,动手实践过后,记录在此。
--user表 Create Table: CREATE TABLE `user` ( `id` int(11) NOT NULL AUTO_INCREMENT, `username` varchar(45) DEFAULT NULL, `userpass` varchar(45) DEFAULT NULL, `profile_id` int(11) DEFAULT NULL, PRIMARY KEY (`id`), KEY `fk_msjy_user_1_idx` (`profile_id`), CONSTRAINT `profile_id` FOREIGN KEY (`profile_id`) REFERENCES `msjy_profile` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION ) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8 --profile表 Create Table: CREATE TABLE `msjy_profile` ( `id` int(11) NOT NULL AUTO_INCREMENT, `status` tinyint(4) DEFAULT NULL, `address` varchar(45) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8
接下来,gii生成user和profile模型
然后gii生成RegisterController并整理成如下:
class RegisterController extends Controller { public function actionIndex() { $this->render('index'); } public function actionCreate() { $modelA = new User; $modelB = new Profile; if(isset($_POST['User']) && isset($_POST['Profile'])) { $modelA->attributes=$_POST['User']; $modelB->attributes=$_POST['Profile']; if($modelA->validate() && $modelB->validate()) { if ($modelB->save(false)) { $modelA->profile_id = $modelB->id; if ($modelA->save(false)) { $this->redirect(array('User/view','id'=>$modelA->id)); } } } } $this->render('create',array( 'modelA'=>$modelA, 'modelB'=>$modelB, )); } }
在views里的register包里创建
--create.php <?php echo $this->renderPartial('_form', array('modelA'=>$modelA,'modelB'=>$modelB)); ?> _form.php <div class="form"> <?php $form=$this->beginWidget('CActiveForm', array( 'id'=>'User-form', 'enableAjaxValidation'=>false, )); ?> <p class="note">Fields with <span class="required">*</span> are required.</p> <?php echo $form->errorSummary(array($modelA,$modelB)); ?>//注意这里 <div class="row"> <?php echo $form->labelEx($modelA,'username'); ?> <?php echo $form->textField($modelA,'username'); ?> <?php echo $form->error($modelA,'username'); ?> </div> <div class="row"> <?php echo $form->labelEx($modelA,'userpass'); ?> <?php echo $form->textField($modelA,'userpass'); ?> <?php echo $form->error($modelA,'userpass'); ?> </div> <div class="row"> <?php echo $form->labelEx($modelB,'status'); ?> <?php echo $form->textField($modelB,'status'); ?> <?php echo $form->error($modelB,'status'); ?> </div> <div class="row"> <?php echo $form->labelEx($modelB,'address'); ?> <?php echo $form->textField($modelB,'address'); ?> <?php echo $form->error($modelB,'address'); ?> </div><div class="row"> </div><div class="row buttons"> <?php echo CHtml::submitButton($modelA->isNewRecord ? 'Create' : 'Save'); ?> </div> <?php $this->endWidget(); ?> </div>
另外,关于create方法里的验证,原文有说明,此处省略文字若干。。。。。