i 被设为模型服务特征,可与所有模型一起使用
有些模型使用softDelete,但有些则没有。
如何通过检查模型是否包含列deleted_at
来检查模型是否具有softDeletes能力
这是我要检查的代码
$isSoftDeleted = \Schema::hasColumn($model->getTable(), 'deleted_at');
这是一个好方法吗?
最佳答案
另一种检查方法(更原始)是检查方法 forceDelete
是否存在。
方法 1 - 检查 forceDelete
方法是否存在
if(method_exists($model, 'forceDelete')){
// Do your stuff here
}
这又是一个小技巧。
方法 2 - 使用界面
通常,使用 insanceof
检查模型是否使用特征并不是最佳选择,从技术上讲,创建一个接口(interface) UsesSoftDeletes
并使模型实际上使用 SoftDeletes 特征来实现它。为此,您可以简单地使用 instanceof
运算符进行检查。
一个例子:
interface UsesSoftDeletes{
//
}
然后在你的模型中
class User extends Model implements UsesSoftDeletes
{
use SoftDeletes;
}
然后检查
if($model instanceof UsesSoftDeletes){
// Do your stuff here
}
编辑 - 检查全局范围
您还可以检查模型是否使用 SoftDeletingScope
类 (Laravel 5.x)。
if($model->hasGlobalScope('Illuminate\Database\Eloquent\SoftDeletingScope')){
// Do your stuff
}
关于laravel - 如何在 laravel 5.4 中检查模型使用软删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45477992/