繁体   English   中英

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

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

在 Laravel 5.1 中,是否有一种很好的方法来检查 eloquent 模型对象是否已被软删除? 我不是在谈论选择数据,但是一旦我有了对象,例如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');
 }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM