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

时间:2019-05-31 12:00:06

标签: laravel eloquent soft-delete

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

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

我该怎么做?

4 个答案:

答案 0 :(得分:1)

您可以编写一个挂接到restored事件的观察者:

 <?php

namespace App\Observers;

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

}

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

Data::observe(DataObserver::class);

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

答案 1 :(得分:0)

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

仅在恢复时才需要注意,将deleteed_at列设置为null 因此,如果您要更新其他字段,只需在还原后执行更新字段的常规操作即可

喜欢这个

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

答案 2 :(得分:0)

要实现此目的,您可以在数据模型中创建函数,这将为您完成此任务。

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

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

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

就是这样。

答案 3 :(得分:0)

这将起作用

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