在Yii中保存模型后,在多个表中保存多条记录


Save multiple records in multiple tables after save model in Yii

我有以下表格:

  1. tbl_project ( id ,描述)
  2. tbl_operation ( id , project_id ,名字)
  3. tbl_itemType ( id , operation_id ,名字)
  4. tbl_item ( id , itemType_id 、名称、单位、价格)

我想当我创建一个新项目时,它在tbl_operation中添加一些操作,然后在tbl_itemType中添加一些itemTypes,然后在tbl_item中添加一些项目。我如何在afterSave()项目模型的行为?

我读了下面的链接,但我不知道这是可能的吗?

esaverelatedbehavior

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
}

您可以利用这些关系。只有当各自的关系只包含要保存的模型时,这种方法才会起作用。在控制器中输入

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

每个操作模型也可以有相应的itemTypes

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

最后每个itemType可以有相应的items

在你的afterSave for操作中有

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

对于afterSave,对于OperationItemType类应依次分别保存相关的ItemType s和Item s。

最好使用afterSave()函数,我想它会为你工作