Laravel自定义软删除还原无法正常工作

时间:2019-04-25 08:32:12

标签: laravel-5 model soft-delete

向Larave软删除功能添加新列fromLast = TRUE个小整数。

deleted_flag

模型的迁移

trait  CustomSoftDeleteTrait
{
    use SoftDeletes;

    protected function runSoftDelete()
    {
        $query = $this->setKeysForSaveQuery($this->newModelQuery());

        $time = $this->freshTimestamp();

        $columns = [$this->getDeletedAtColumn() => $this->fromDateTime($time)];

        $this->{$this->getDeletedAtColumn()} = $time;

        if ($this->timestamps && ! is_null($this->getUpdatedAtColumn())) {
            $this->{$this->getUpdatedAtColumn()} = $time;

            $columns[$this->getUpdatedAtColumn()] = $this->fromDateTime($time);
        }

        $columns[$this->getDeletedFlagColumn()] = 1; //<-- here is the deleting

        $query->update($columns);
    }

    protected function restore()
    {            
        if ($this->fireModelEvent('restoring') === false) {
            return false;
        }

        $this->{$this->getDeletedFlagColumn()} = 0; //<-- here is restoring
        $this->{$this->getDeletedAtColumn()} = null;    

        $this->exists = true;

        $result = $this->save();

        $this->fireModelEvent('restored', false);

        return $result;
    }

    public function getDeletedFlagColumn()
    {
        return defined('static::DELETED_FLAG') ? static::DELETED_FLAG : 'deleted_flag';
    }
}

在模型中使用自定义特征,

Schema::create('families', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name');
            $table->integer('family_type');

            $table->timestamp('create_date')->nullable();
            $table->timestamp('update_date')->nullable();
            $table->timestamp('delete_date')->nullable();
            $table->tinyInteger('delete_flg')->nullable();
        });

使用class Family extends Model { use CustomSoftDeleteTrait; protected $guarded = [ 'id', ]; const CREATED_AT = 'create_date'; const UPDATED_AT = 'update_date'; const DELETED_AT = 'delete_date'; const DELETED_FLAG = 'delete_flg'; } 删除模型时,同时设置了$family->delete()delete_date列。恢复模型后,只有一个字段delete_flg设置为null。 delete_date字段保持为1。

1 个答案:

答案 0 :(得分:0)

这是一个相当“棘手”的错误。

但是您要做的就是在自定义特征中将restore()函数的修改器从protected更改为public。

  protected function restore() { /**/ }

应该变成

  public function restore() { /**/ }

不能从您的家庭模型中访问受保护的功能。因此,PHP仅使用Eloquent Soft Delete Trait中的原始restore()方法。