简体   繁体   English

YII模型可处理多个表

[英]YII model to handle more than one table

I am developing a registration form in YII. 我正在YII中开发注册表。 In my form there is a radio option to choose register as Mode1 or register as Mode2. 在我的表单中,有一个单选选项可以选择“注册为模式1”或“注册为模式2”。 If user chooses mode1, data's should be entered to table1 or it should entered to table2. 如果用户选择模式1,则应将数据输入表1或将数据输入表2。 In YII each model deals with one table. 在YII中,每个模型都处理一个表。 Here my form deals with two tables. 在这里,我的表格处理两个表。

So how to handle such a form to validate and enter data's to table in YII? 那么如何处理这样的表格来验证并在YII中将数据输入表格呢?

The easiest way is to create one model for the form (assuming they have the same fields?) This class would extend CFormModel (in the example below I refer to this model as GlobalFormModel ) 最简单的方法是为表单创建一个模型(假设它们具有相同的字段?)此类将扩展CFormModel (在下面的示例中,我将此模型称为GlobalFormModel

This model would have the same attributes as the other two models, as well as one new attribute called mode When the form is submitted, in the controller you can handle it based on which mode and validate it against the correct model, eg: 该模型将具有与其他两个模型相同的属性,以及一个称为mode的新属性。提交表单后,您可以在控制器中根据哪种模式处理它,并针对正确的模型进行验证,例如:

$model = new GlobalFormModel

if(isset($_POST['GlobalFormModel'])){
    $model->attributes = $_POST['GlobalFormModel']; 

    if ($model->mode == 1){
        $newmodel = new FormOne;
        $newmodel->attributes = $model->attributes;
    } else {
         $newmodel = new FormTwo;
         $newmodel->attributes = $model->attributes;
    } 

    ... // validate and save $newmodel
}

$this->render("yourview",array("model"=>$model));

Where FormOne is the model associated with the first table, and FormTwo is associated with the second table. 其中,FormOne是与第一个表关联的模型,而FormTwo是与第二个表关联的模型。 First you create a new instance of the GlobalFormModel (which is passed to the view). 首先,您创建一个GlobalFormModel的新实例(传递给视图)。 You check if the form has been submitted (you could validate it here or after loading one of the two models, that is your choice). 您检查表单是否已提交(可以在此处进行验证,也可以在加载两个模型之一后进行验证)。 You check the mode, and then load the correct model. 您检查模式,然后加载正确的模型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM