Describe the feature

Model A has many Prev-Model-A and many Next-Model-A, e.g. Task, PrevTasks, NextTasks

If Task was deleted, NextTasks should be able to be deleted by cascade.

Motivation

Related Issues

6346, #6344, go-orm/playground PR

Comment From: pplmx

FYI.

Here is a demo implemented by Spring JPA, which implements the above requirement.

Comment From: Shahriar-Sazid

You can use AfterDelete hook to implement this.

func (t *Task) AfterDelete(tx *gorm.DB) (err error) {
    tx.Clauses(clause.Returning{}).Where("prev_id = ?", t.ID).Delete(&TaskDepends{})
    return
}

Comment From: pplmx

Hi, @Shahriar-Sazid Sorry for the late reply. 1. It seems that the function you supply only deletes the TaskDepends Record, while its next_deps in Task table don't be deleted, Right? 2. You use TaskDepends struct, which is not defined in my code, so I use this solution to clear the relationship(It still cannot delete the records in Task)

func (t *Task) AfterDelete(tx *gorm.DB) (err error) {
    if err = tx.Model(t).Association("PrevDeps").Clear(); err != nil {
        return
    }
    if err = tx.Model(t).Association("NextDeps").Clear(); err != nil {
        return
    }
    return
}

Comment From: Shahriar-Sazid

I think your attached snippet worked properly. Right?

Comment From: pplmx

I think your attached snippet worked properly. Right?

Yes

Comment From: pplmx

FYR. https://github.com/go-gorm/gorm/issues/6357#issuecomment-1639161159