Is it possible to perform “future” soft delete in laravel?

走远了吗. 提交于 2019-12-25 01:47:00

问题


I found that the soft-delete in laravel Eloquent ORM is just replacing the null in deleted_at column by a timestamp. When querying a table with soft delete, is it just checking if the deleted_at is null, or it is really comparing the value with current time?

I am asking to see if I am able to do schedule delete by setting a future time on the deleted_at column.


回答1:


Laravel only checks if deleted_at is not NULL. SoftDeletingScope:

public function apply(Builder $builder)
{
    $model = $builder->getModel();

    $builder->whereNull($model->getQualifiedDeletedAtColumn());

    $this->extend($builder);
}

You can change that by creating your own SoftDeletingScope and SoftDeletingTrait (it's called SoftDeletes in Laravel 5).

trait MySoftDeletingTrait {
    use Illuminate\Database\Eloquent\SoftDeletingTrait;

    public static function bootSoftDeletingTrait()
    {
        static::addGlobalScope(new MySoftDeletingScope);
    }
}

And

class MySoftDeletingScope extends Illuminate\Database\Eloquent\SoftDeletingScope {
    public function apply(Builder $builder)
    {
        $model = $builder->getModel();

        $builder->where($model->getQualifiedDeletedAtColumn(), '<=', Carbon::now());

        $this->extend($builder);
    }
}

Note that to be able to remove the scope (the remove() method) you would have to override more of the original scope class. At least also isSoftDeleteConstraint, but I'll leave that to you.

Finally you only have to switch out the trait that you use in your models:

use MySoftDeletingTrait;


来源:https://stackoverflow.com/questions/28693284/is-it-possible-to-perform-future-soft-delete-in-laravel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!