[英]Laravel Eloquent - Model::all() method give all result including soft deletes
[英]How to disable soft deletes in Laravel 5.8 Eloquent model
在我的项目中,所有模型都扩展了BaseModel
类, SoftDeletes
默认使用SoftDeletes
特性。 但是在某些特定情况下,例如在类ShouldHardDelete
我不希望我的数据库记录被软删除。 让我们假设,我不能否认扩展BaseModel
。
我应该在我的ShouldHardDelete
类中进行哪些更改以防止它使用软删除?
你应该做两件事:
SoftDeletes
trait 中有一个静态方法bootSoftDeletes()
,它初始化模型的软删除行为: /**
* Boot the soft deleting trait for a model.
*
* @return void
*/
public static function bootSoftDeletes()
{
static::addGlobalScope(new SoftDeletingScope);
}
在ShouldHardDelete
类中将其覆盖为空方法:
/**
* Disable soft deletes for this model
*/
public static function bootSoftDeletes() {}
ShouldHardDelete
$forceDeleting
字段设置$forceDeleting
true
: protected $forceDeleting = true;
因此,您可以禁用软删除的行为,同时还延长BaseModel
它使用SoftDeletes
特质。
如果您正在使用softDelete
特征但不想在特定查询中使用它,那么您可以在模型中使用withoutGlobalScope
方法。
User::withoutGlobalScope(Illuminate\Database\Eloquent\SoftDeletingScope::class)->get();
如果您想对特定查询使用多个模型,那么最好在AppServiceProvider
扩展 eloquent builder
public function boot()
{
Builder::macro('withoutSoftDeletingScope', function () {
$this->withoutGlobalScope(Illuminate\Database\Eloquent\SoftDeletingScope::class);
return $this;
});
}
然后你可以在任何模型中作为方法调用
User::withoutSoftDeletingScope()->get();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.