如何始终使用withTrashed()进行模型绑定 [英] How to always use withTrashed() for model Binding

查看:1141
本文介绍了如何始终使用withTrashed()进行模型绑定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用程序中,我对许多对象使用了软删除,但是我仍然想在我的应用程序中访问它们,只是显示一条特殊消息,表明该项目已被删除并有机会还原它.

In my app, I use soft delete on a lot of object, but I still want to access them in my app, just showing a special message that this item has been deleted and give the opportunity to restore it.

当前,我必须对RouteServiceProvider中的所有路由参数执行此操作:

Currently I have to do this for all my route parametters in my RouteServiceProvider:

    /**
     * Define your route model bindings, pattern filters, etc.
     *
     * @return void
     */
    public function boot()
    {


        parent::boot();

        Route::bind('user', function ($value) {
            return User::withTrashed()->find($value);
        });

        Route::bind('post', function ($value) {
            return Post::withTrashed()->find($value);
        });

        [...]


    }

是否有更快更好的方法将被破坏的对象添加到模型绑定中?

Is there a quicker and better way to add the trashed Object to the model binding ?

推荐答案

Jerodev的答案对我不起作用. SoftDeletingScope继续筛选出已删除的项目.因此,我只是覆盖了该范围和SoftDeletes特性:

Jerodev's answer didn't work for me. The SoftDeletingScope continued to filter out the deleted items. So I just overrode that scope and the SoftDeletes trait:

SoftDeletingWithDeletesScope.php:

namespace App\Models\Scopes;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletingScope;

class SoftDeletingWithDeletesScope extends SoftDeletingScope
{
    public function apply(Builder $builder, Model $model)
    {
    }
}

SoftDeletesWithDeleted.php:

namespace App\Models\Traits;

use Illuminate\Database\Eloquent\SoftDeletes;
use App\Models\Scopes\SoftDeletingWithDeletesScope;

trait SoftDeletesWithDeleted
{
    use SoftDeletes;

    public static function bootSoftDeletes()
    {
        static::addGlobalScope(new SoftDeletingWithDeletesScope);
    }
}

这实际上只是删除了过滤器,同时仍然允许我使用其余的所有SoftDeletingScope扩展名.

This effectively just removes the filter while still allowing me to use all the rest of the SoftDeletingScope extensions.

然后在我的模型中,我用新的SoftDeletesWithDeleted特征替换了SoftDeletes特征:

Then in my model I replaced the SoftDeletes trait with my new SoftDeletesWithDeleted trait:

use App\Models\Traits\SoftDeletesWithDeleted;

class MyModel extends Model
{
    use SoftDeletesWithDeleted;

这篇关于如何始终使用withTrashed()进行模型绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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