Laravel force delete event on relations

时光毁灭记忆、已成空白 提交于 2019-12-08 03:05:58

问题


I'm developing a Laravel web app using Laravel 5.2. My question is very simple... How do I listen to a forceDelete event in order to forceDelete model relations?

I've been looking around the web and S.O. for a few but all the questions/answers I've found where releted to the delete method, and also in the API documentation I haven't found very much...

In my case I have a Registry model and a RegistryDetail model

Registry table

|id|name|surname|....

RegistryDetail table

|id|id_registry|....

I've created for both this boot function:

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

    static::deleted(function($registry) {
        // Delete registry_detail
        $registry->registryDetail->delete();
    });

    static::restored(function($registry) {
        // Restore registry_detail
        $registry->registrydetail()->withTrashed()->restore();
    });
}

Since both models have SoftDeletes the static::deleted function is called only when the delete() method is called. if I call a forceDelete() method the related model won't be deleted from the database.

If you need more informations let me know.

Thanks in advance


回答1:


The deleted event should still fire when calling forceDelete(). Inside the deleted() event method, you can check the the forceDeleting protected property via isForceDeleting() to see if you're in a regular delete or a forced delete.

static::deleted(function($registry) {
    // Delete registry_detail
    if ($registry->isForceDeleting()) {
        $registry->registryDetail->forceDelete();
    } else {
        $registry->registryDetail->delete();
    }
});


来源:https://stackoverflow.com/questions/34952259/laravel-force-delete-event-on-relations

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!