确定在事件处理程序Laravel中是否是软删除

时间:2016-05-10 14:43:15

标签: php laravel

我有这个事件处理程序:

protected static function boot() {
    parent::boot();

    static::deleting(function($user) { // before delete() method call this
        $user->comments()->delete();

    });
}

当我使用$user->forceDelete();$user->delete();时,会触发此事件并删除所有评论。这不行,因为我希望仅在$user->forceDelete();上触发此事件。在我的情况下,其他表没有实现软删除

2 个答案:

答案 0 :(得分:2)

您可以检查模型上的forceDeleting属性。如果您正在执行forceDelete

,则会设置(和为真)
static::deleting(function($user) { // before delete() method call this
    if ($user->forceDeleting) {
        $user->comments()->delete();
    }
});

答案 1 :(得分:0)

在模型类中(例如):

public static function boot() {
    
    parent::boot();
    
    static::created(function($item){
        Log::info("Model Created:".get_class($item)."-ID-".$item->id.'-by user: '.Auth::id());
    });
    
    static::updated(function($item){
        Log::info("Model Updated:".get_class($item)."-ID-".$item->id.'-by user: '.Auth::id());
    });
    
    static::deleted(function($item){
        Log::info("Model Soft Delete:".get_class($item)."-ID-".$item->id.'-by user: '.Auth::id());
    });

    static::forceDeleted(function($item){
        Log::info("Model Force Delete:".get_class($item)."-ID-".$item->id.'-by user: '.Auth::id());
    });
    
}