Laravel 5.5在模型上的自定义软删除 [英] Laravel 5.5 Custom Soft Deletes on Model

查看:522
本文介绍了Laravel 5.5在模型上的自定义软删除的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通过status列中的值将我的帖子定义为是否软删除.其中:0 =不可用,1 =可用,77 =软删除.

My posts are defined as soft deleted or not via the value in the status column, where: 0 = unavailable, 1 = available, and 77 = soft deleted.

当前,我在模型中添加了一个全局范围,以确保不返回软删除的帖子:

Currently, I add a global scope in the model to make sure I don't return soft-deleted posts:

protected static function boot()
{
    parent::boot();

    static::addGlobalScope('status', function (Builder $builder) {
        $builder->where('status', '!=', '77');
    });
}

如何使用默认的timestamps和delete_at列修改模型的softDelete(laravel内置功能)以使用我的基于数字/状态的系统,使其在使用->delete()之类的方法时甚至可以工作,甚至可以工作,->withTrashed()->restore()?

How would I modify softDelete (laravels built-in functionality) of a model from its default of timestamps and deleted_at columns to use my number/status based system, to work even/especially when using methods such as ->delete(), ->withTrashed(), and ->restore()?

推荐答案

您可以查看Laravel的模型事件部分.在模型中,扩展您创建的baseModel类.在此baseModel中,您可以添加在删除模型时触发的事件.像这样:

You can check out the model events part of Laravel. In your models, extend a baseModel class that you make. In this baseModel you can add an event that is triggered on model delete. Like so:

protected static function boot(){
    static::deleting(function($thisModel){
        $thisModel->attributes['status'] = 77;
        $thisModel->save();
        return false;
    });
}

返回false时,将停止用于删除模型的默认操作.因此,这会将状态设置为77,而不是将其删除.或者,您可以只在要使用这种删除方式的任何模型中使用它,而不是使用基本模型.我发现对于具有一些实现基于状态的软删除功能的大型项目而言,基本模型更容易些.

When you return false, you stop the default operation for deleting the model. So this will instead set the status to 77 instead of removing it. Or you could just use that in any model you want to use this sort of deleting, instead of using a base model. I find the base model to be easier for large projects that have a few things that would implement status based soft deletes.

要在此模型上添加其他类似软删除的功能,请考虑使用局部作用域而不是列出的全局作用域.例如:

To expand on adding other soft-delete like functions to this model consider using local scopes instead of the listed global one. For example:

public function scopeOnlyTrashed(Builder $query){
    return $query->where('status', 77);
}

现在,当您进行数据库调用时

Now when you do the database call

Posts::onlyTrashed()->get();

您将获得与laravel的onlyTrashed()方法相同的功能.

you will get the same functionality as the laravel's onlyTrashed() method.

这篇关于Laravel 5.5在模型上的自定义软删除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆