0

I have a relation between Categories and Expenses. An Expense belongsTo a Category, and it's linked using a foreign key in the database. Whenever I delete a category, all linked expenses will be deleted as well, as expected.

Now, I also have a relation between an Expense, and many Transactions, using a One-to-Many polymorphic relation. Using the method below, when I delete an Expense, all Transactions will be deleted with it, as expected.

But, when I delete a Category, all Expenses will be deleted as well as expected, but not the Transactions from either Expense. Why is this and how can I make sure all Transactions are deleted as well for all Expenses, when I delete a Category?

Deleting event in Expense model:

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

    static::deleting(function($expense) {
        $expense->transactions()->delete();
    });
}

Relation Expense -> Transactions:

public function transactions()
{
    return $this->morphMany(Transaction::class);
}
Kara
  • 6,115
  • 16
  • 50
  • 57
Hardist
  • 2,098
  • 11
  • 49
  • 85
  • Create [MySQL trigger](https://dev.mysql.com/doc/refman/5.7/en/triggers.html) for that. Check [this](https://stackoverflow.com/questions/21301391/how-to-delete-automatically-all-reference-rows-if-parent-row-get-deleted-in-mysq) q/a. – Tpojka Jul 18 '17 at 18:36
  • 1
    First thing is to see is if Expense::deleting event is fired at all when you delete a Category. If not, maybe you can force the cleanup from your Category::deleting event handler? – ivanhoe Jul 18 '17 at 22:17
  • Yeah I was thinking about that, but I have more than just Category that is related to an Expense. But I should indeed check if it's fired at all, but I guess not, otherwise it should work. Will still start checking from there :) – Hardist Jul 19 '17 at 04:50

0 Answers0