Saving Multiple Models, If One Of Them Fails, Rollback

As the title says.

I have an action where multiple models are used and data is stored in everyone of them.

It’s something like this:




$model1->save()

    then assign attributes to $model2

    $model2->save()

        then assign attributes to $model3

        $model3->save()



Everything is working, but if the 2nd or the 3rd model fails lets say because some data is missing, the first model will be saved and the rest won’t.

Is there any way to do a roll back if any of them failed?

In your action:




    $transaction = Yii::app()->db->beginTransaction();


    try

    {

        if (!$model1->save())

            throw new Exception('Failed to save model 1');


        if (!$model2->save())

            throw new Exception('Failed to save model 2');


        // etc...


        $transaction->commit();


        // You can handle success messages and redirection here

    }

    catch (Exception $ex)

    {

        $transaction->rollback();

    }



What Keith said plus see these couple of official documentation on this: first (generic transaction SQL usage) and second (AR with transactions. probably closer to what you want).