使用yii保存事务中的多条记录:不使用循环


saving multiple records with transaction using yii :not using loop

我有这样的东西:

public function actionCreate() {
    $a = new Tblcompany;
    $c = new Tblfunctioncontrol;
    $transaction= Yii::app()->db->beginTransaction();
    // Uncomment the following line if AJAX validation is needed
    // $this->performAjaxValidation($model);
    try {
      if(isset($_POST['Tblcompany'])) {
        $a->attributes=$_POST['Tblcompany'];
        //}
        if($a->save()){
           //1st row       
           $c->company_code= $a->company_code;
           $c->usergroup_code= 'Admin';
           $c->function_code= 'M01-01-01';
           $c->description= 'Vehicle Setup';
           $c->hide_key= false;
           $c->add_key= true;
           $c->edit_key= true;
           $c->delete_key= true;
           $c->print_key= true;

现在,我还想包括另一行的c

    //2nd row
           $c->company_code= $a->company_code;
           $c->function_code= 'M01-01-02';
           $c->description= 'Make Setup';
           $c->hide_key= FALSE;
           $c->add_key= TRUE;
           $c->edit_key= True;
           $c->delete_key= true;
           $c->print_key= true;

所以,我想在这里包括两行$c。需要一些关于如何做到这一点的解释…

使用两个数组来输入这种需求。

$arr1 = array("field_name" => "value","field_name" => "value");
$arr2 = array("field_name" => "value","field_name" => "value");

现在做这样的事情。

$model = new Model;
$model->attributes = $arr1;
$model->save();
$model = new Model;
$model->attributes = $arr2;
$model->save();

这将在没有for循环的情况下向数据库中插入两个值。

您正在做的是更改$c引用的实体。您正在用第二行的值覆盖第一行的值。要创建第二行,只需为第二行创建一个新对象,如下所示:

//2nd row
$c= new Tblfunctioncontrol;
$c->company_code= $a->company_code;
$c->function_code= 'M01-01-02';
$c->description= 'Make Setup';
$c->hide_key= FALSE;
$c->add_key= TRUE;
$c->edit_key= True;
$c->delete_key= true;
$c->print_key= true;
$c->save();

我在您的代码中没有看到$c->save()的调用。我想你只是没有贴出来?不管怎样,你必须把它称为你的第一个和第二个$c