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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34003284/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 23:42:11  来源:igfitidea点击:

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

phplaraveleloquentlaravel-5.1soft-delete

提问by DisgruntledGoat

In Laravel 5.1 is there a nice way to check if an eloquent model object has been soft-deleted? I'm not talking about selecting data but once I have the object e.g. Thing::withTrashed()->find($id)

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

So far the only way I can see is

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

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

I do not see any relevant method in the APIthat would allow for example

在 API中看不到任何相关的方法例如

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

回答by DisgruntledGoat

Just realised I was looking in the wrong API. The Model class doesn't have this, but the SoftDelete traitthat my models use has a trashed()method.

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

So I can write

所以我可以写

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

回答by tanvir993

In laravel6, you can use followings.

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

To check the Eloquent Model is using soft delete:

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

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

To check the Eloquent Model is using soft delete in resource (when using resource to response):

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

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

And finally to check if the model is trashed:

最后检查模型是否被丢弃:

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

Hope, this will be helpful!

希望,这会有所帮助!