How to chain delete hook?

I have multiples models a,b,c
So, when deleting entries from model a , i have added a after delete hook. which delete related entries from model b.
I want to add a second delete hook in model b which will delete related entries from model c. Which should be activated when i delete a entry from model a.

I need to chain delete hooks across multiple model.

In laravel it we have

class User extends Eloquent
{
    public function photos()
    {
        return $this->has_many('Photo');
    }

    // this is a recommended way to declare event handlers
    public static function boot() {
        parent::boot();

        static::deleting(function($user) { // before delete() method call this
             $user->photos()->delete();
             // do the rest of the cleanup...
        });
    }
}

is there a similar method is in Adonis?

1 Like

Hello @muneeb-ashlar!

There are similar things indeed :yum:

https://adonisjs.com/docs/4.1/database-hooks#_lifecycle_events

You could also take a look if your database itself provides such things. Like ON DELETE CASCADE etc. Might make things simpler

2 Likes

I added the cascade deletion in migration but dont know why it stopped working now i have added these life cycle hooks but when i use the following it does not chain to other hooks i added in second model.
Means when this hooks is called “Notes” model hook is not executed.

static boot () {
        super.boot()
        this.addHook('afterDelete', async modelInstance => {
            try {
                await modelInstance.Notes().delete()
            } catch (error) {
                console.log(error.message)
            }
        })
    }

Like @McSneaky said, you are trying to reinvent the wheel - something which your DB can handle very well without you thinking about it.

Share the migration files of all the schemas concerned. Let’s see why the onDelete(‘cascade’) condition isn’t working for you.

Cheers.