SADi
SADi

Reputation: 295

Save multiple records in multiple tables after save model in Yii

I have the followings tables:

  1. tbl_project(id, description)
  2. tbl_operation(id, project_id, name)
  3. tbl_itemType(id, operation_id, name)
  4. tbl_item(id, itemType_id, name, unit, price)

I wanna when i create a new project, it adds some operations in tbl_operation and then adds some itemTypes to tbl_itemType and then adds some items in tbl_item. How can i do it in afterSave() behavior of project's model?

I read the following link, but i don't know is it possible to do by this?

esaverelatedbehavior

Upvotes: 1

Views: 389

Answers (3)

Ambarish Patra
Ambarish Patra

Reputation: 21

Better use afterSave() function , i think it will work for you

Upvotes: 1

topher
topher

Reputation: 14860

You could make use of the relations. This approach will only work if the respective relation contains only the models to be saved. In your controller have

$project->operations = array(/*your operations*/);

In turn each operation model could also have the related itemTypes

$operation->itemTypes = array(/*itemTypes for this operation*/)

And lastly each itemType could have the related items.

And in your afterSave for operations have

public function afterSave() {
    foreach ($this->operation as $op) {
        $op->project_id = $model->id;
        $op->save();
    }
    return parent::afterSave();
}

For the afterSave for the Operation and ItemType classes should in turn save the related ItemTypes and Items respectively.

Upvotes: 1

Developerium
Developerium

Reputation: 7265

just create a function in your ProjectModel

public function afterSave()
{
   $operation_model = new Operation();
   $operation_model->setAttributes($YOUR_DATA);
   $operation_model->save(); // create your operation

   // same goes for every other data you want to save

    return parent::afterSave(); // keep the chain
}

Upvotes: 1

Related Questions