how do I INSERT data into multiple tables at once?

hi all,

 i have a problem in understanding how to INSERT data into multiple tables at once?

i have 2 tables.

table A(id,a1)

table B(id,b1)

i tried the code in controller for create()


public function actionCreate()

	{

		$model=new A;

          $b=new B;

		// Uncomment the following line if AJAX validation is needed

		// $this->performAjaxValidation($model);


		if(isset($_POST['A'], $_POST['B']))

		{

			$model->attributes=$_POST['A'];

			 $b->attributes=$_POST['B'];

			if($model->save())

				$this->redirect(array('view','id'=>$model->id));

				if($b->save())

				$this->redirect(array('view','id'=>$b->id));

		}

         // validate BOTH $a and $b

        $valid=$model->validate();

        $valid=$b->validate() && $valid;


        if($valid)

        {

            // use false parameter to disable validation

            $model->save(false);

            $b->save(false);

            // ...redirect to another page

        }


		$this->render('create',array(

			'b'=>$b,

			'model'=>$model,


		));

	}

i created a from containing both a1 and b1 in it.

the problem is , the data is getting inserted indivdually for both the table.

for example if i insert data for either a1 or b1 , any one is getting inserted.

But if i insert both a1 and b1 then only a1 is getting inserted.

help me please…

When you insert that in A, as it is validated first and REDIRECTED after, B never reaches its save method.




$model->attributes=$_POST['A'];

    $b->attributes=$_POST['B'];

    if($model->save())

          $this->redirect(array('view','id'=>$model->id)); // HERE

    if($b->save()) // IF ABOVE OCCURS, THEN THIS IS NOT REACHED

          $this->redirect(array('view','id'=>$b->id));




I suggest you review your code or execute save() before any redirection




if(isset($_POST['a'])){

     $model->attributes = $_POST['a'];


    $result_a = $model->save();

}

if(isset($_POST['b'])){

     $b->attributes = $_POST['b'];

    $result_b = $model->save();

}


// now handle redirections... 



Also when working with multiple records at once it’s good to use transactions.

1 Like

oh thanks alot, needed that.

Could you expand on this? I’m surprised how hard it seems to be to write to multiple tables. None of the examples I’ve seen work for me, for reasons I’ve yet to figure out.