Yii 1 - deleting row after saving row in other table

802 Views Asked by At

I have 2 tables with the following structure:

Store(name, model, serial_number)
Work(name, model, serial_number, adress)

When I add a record to table Work I get data with ListData from table Store. The problem is: How can I delete the row from Store after I save it to Work?

public function actionCreate()
{

    $model=new Work;

    // Uncomment the following line if AJAX validation is needed
    // $this->performAjaxValidation($model);

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

        if($model->save()) {

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



        }

    }

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

        ));

}

I tried to write querys in if($model->save) block, but I don't know how to delete the row by serial_number.

I think I should use transactions, but I don't know how to use it in my example.

1

There are 1 best solutions below

0
On BEST ANSWER

You need to identify your store for deleting it. You did not explain what's the relationship between these two models. If the serial_number field from two models is the same, you can find the store with serial_number of work and then delete it. In this case you can do the following:

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

    if($model->save()) {
        Store::model()->deleteAll("serial_number = " . $model->serial_number);
        $this->redirect(array('view','id'=>$model->id));

    }

}

Otherwise, you should define relation between two models.