如何在Eloquent中检查行是否被软删除


How to check if row is soft-deleted in Eloquent?

在Laravel 5.1中,是否有一种很好的方法来检查一个有说服力的模型对象是否已被软删除?我说的不是选择数据,而是一旦我有了对象,例如Thing::withTrashed()->find($id)

到目前为止,我唯一能看到的是

if ($thing->deleted_at !== null) { ... }

我在API中没有看到任何相关的方法允许例如

if ($thing->isDeleted()) { ... }

我刚刚意识到我查找了错误的API。Model类没有这个,但我的模型使用的SoftDelete特性有一个trashed()方法。

所以我可以写

if ($thing->trashed()) { ... }

在laravel6中,您可以使用以下内容。

要检查Eloquent模型是否使用软删除:

if( method_exists($thing, 'trashed') ) {
    // do something
}

要检查Eloquent模型是否在资源中使用软删除(当使用资源进行响应时):

if( method_exists($this->resource, 'trashed') ) {
    // do something
}

最后检查模型是否被破坏:

if ($thing->trashed()) {
    // do something
}

希望,这会有所帮助!

对于那些在测试环境中寻求答案的人,在laravel的测试用例中您可以断言为:

$this->assertSoftDeleted($user);

或者如果它刚刚被删除(没有软删除)

$this->assertDeleted($user);

这是的最佳方式

$model = 'App''Models''ModelName';
$uses_soft_delete = in_array('Illuminate'Database'Eloquent'SoftDeletes', class_uses($model));
if($usesSoftDeletes) {
    // write code...
}

这对我有效

$checkDomain = Domain::where('tenant_id', $subdomain)->withTrashed()->first();
                
 if($checkDomain->trashed()){
       return redirect()->route('domain.not.found');
 }else{
     return view('frontend.' . theme() . '.index');
 }