繁体   English   中英

如何使用另一列恢复软删除?

[英]how to restore soft delete with one more column?

我有一个名为data的表,我正在使用软删除来删除记录。我的数据表中还有一个字段,当删除记录时也会更新该字段。 但是当我恢复该软删除的记录时,它会更新我的Deleted_at字段,但不会更新其他字段。 我用这个代码

Data::withTrashed()->find($id)->restore();

我怎样才能做到这一点?

您可以编写一个与已restored事件挂钩的观察器:

 <?php

namespace App\Observers;

class DataObserver
{
    public function restored($data)
    {
        // Update field here
    }

}

当然还要注册一个服务提供者的boot()方法:

Data::observe(DataObserver::class);

注意:根据时间,您可能更喜欢restoring事件

Data::withTrashed()->find($id)->restore();

这意味着仅用于还原,将Deleted_at列设置为null,因此,如果要更新其他字段,只需在还原后执行常规操作即可更新字段

像这个

Data::withTrashed()->find($id)->restore();
Data::find($id)->update($array);

为此,您可以在数据模型中创建函数,该函数将为您实现。

public function restoreItem()
{
    $this->deleted_at = null;
    $this->other_field = null;
    $this->save();
}

现在您需要在控制器中调用它:

Data::withTrashed()->find($id)->restoreItem();

而已。

这会起作用

Data::withTrashed()->whereId($id)->update([
    'deleted_at'=>null,
    'other_column'=>$value,
]);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM