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

Mat*_*rre 5 laravel eloquent laravel-5.5

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

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

        [...]


    }
Run Code Online (Sandbox Code Playgroud)

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

Chr*_*ris 5

杰罗德夫的回答对我不起作用。继续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)
    {
    }
}
Run Code Online (Sandbox Code Playgroud)

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

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

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

use App\Models\Traits\SoftDeletesWithDeleted;

class MyModel extends Model
{
    use SoftDeletesWithDeleted;
Run Code Online (Sandbox Code Playgroud)


小智 2

对于 Laravel 5.6 至 7

您可以按照此文档https://laravel.com/docs/5.6/scout#soft-deleting。并将配置文件soft_delete的选项设置config/scout.phptrue.

'soft_delete' => true,
Run Code Online (Sandbox Code Playgroud)

对于 Laravel 8+

您可以按照此文档https://laravel.com/docs/8.x/routing#implicit-soft-deleted-models。并附加到->withTrashed()应该接受废弃模型的路线:

前任:

Route::get('/users/{user}', function (User $user) {
    return $user->email;
})->withTrashed();
Run Code Online (Sandbox Code Playgroud)