Yii2 模型的复制 - 行



编辑或更新模型属性时,我不希望更新该记录。相反,应创建新记录并禁用旧记录。 我还有另一个保存旧记录的日志表。

我的代码如下

public function afterSave($insert, $changedAttributes)
{

if ($insert) {
// Да это новая запись (insert)
$model = new Test3log();
$model->desc = $this->desc ;
$model->id_old = $this->id;
$model->isdisabled=1;
$model->save();
} else {
$save = "";
foreach ($changedAttributes as $change => $val) {
if (trim($val) != trim($this->{$change})) {
$save .= $this->attributeLabels()[$change] . '[' . $val . '->' . $this->{$change} . "]n";
}
}
$xx =$this->getoldattributes();
if ($save != "") {
//  Get Old data
// Get New data
// repl new record with old id
// repl old record with new id
$modelnewline = new Test3();
$modelnewline->desc = $xx['desc'];
$modelnewline->id_old = $xx['id'];
$modelnewline->id = NULL;
$modelnewline->isdisabled = 1;
$modelnewline->save();
$newid = $modelnewline->id;
$oldid =$this->id;
$this->isdisabled=1;
$this->id = $newid;
$this->desc = $changedAttributes['desc'];
$this->save(false);
}
}
parent::afterSave($insert, $changedAttributes);
}

你的问题太宽泛了,你没有提到你目前面临的问题到底是什么,但考虑到你是社区的新手,我会尝试以一种你可以相应地翻译它的方式回答它。

最重要的是,您描述的问题需要在模型的beforeSave()中实现,该在插入或更新记录开始时调用,而不是afterSave()因为您的记录已经使用新值进行了更新,您绝对不想这样做。

根据您的要求。

当模型属性被编辑或更新时,我不希望这样 要更新的记录。相反,应该创建一个新记录和旧的 应禁用记录。另外,我还有另一个日志表,其中旧的 记录已保存。

因此,当现有记录的属性更改时,有 3 个主要事项

  • 通过将状态更新为 0 来禁用当前记录。
  • 添加保存新值的新记录。
  • 备份或日志表中添加具有旧值的新记录。

我不会添加实际代码,因为没有太多关于哪些模型进行交互的信息,因此查看要求,我将使用假设我有书籍的场景,每当更改或更新书籍的名称时,它应该添加一个具有新值的新记录并保留旧记录,将status列更改为0以便书籍被禁用,并将旧值备份到表中BooksBackup。所以基本上你会有一个线框来相应地调整你的代码。

您可以根据所使用的模型使用逻辑。

下面是示例架构

  • Books模型

    • name varchar(255)
    • status tinyint(1)
  • BooksBackup模型

    • id int(11)
    • book_id int(11)
    • name varchar(255)

我将在我的Books模型中添加以下beforeSave()函数

public function beforeSave($insert) {
if( !parent::beforeSave($insert) ){
return false;
}
//your custom code
if( !$insert ){
$ifAttributesChanged = (!empty($this->dirtyAttributes) );
//if attributes were changed
if( $ifAttributesChanged ){
//add new record with the new values
$book = new self();
$book->attributes = $this->attributes;
$book->save();
//add back the old values of the changed attributes 
//to the current record so nothing is changed for the current record
foreach( $this->dirtyAttributes as $attribute => $value ){
$this->$attribute = $this->oldAttributes[$attribute];
}
//disable the current record
$this->status = 0;
//backup old record
$backup = new BackupBooks();
$backup->book_id = $this->id;
$backup->name = $this->name;
$backup->save();
}
}
return true;
}

最新更新