gpt4 book ai didi

laravel - 如何始终使用 withTrashed() 进行模型绑定(bind)

转载 作者:行者123 更新时间:2023-12-05 02:17:29 25 4
gpt4 key购买 nike

在我的应用程序中,我对很多对象使用软删除,但我仍然想在我的应用程序中访问它们,只是显示一条特殊消息,表明该项目已被删除并提供恢复它的机会。

目前,我必须为我的 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);
});

[...]


}

有没有更快更好的方法将被破坏的对象添加到模型绑定(bind)中?

最佳答案

Jerodev 的回答对我不起作用。 SoftDeletingScope 继续过滤掉已删除的项目。所以我只是覆盖了那个范围和 SoftDeletes 特性:

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 扩展。

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

use App\Models\Traits\SoftDeletesWithDeleted;

class MyModel extends Model
{
use SoftDeletesWithDeleted;

关于laravel - 如何始终使用 withTrashed() 进行模型绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47749901/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com