Golang GORM Delete with Select

Viewed 2283

I'm trying to cascade delete the below structure:

type Action struct {
    gorm.Model
    Name  string
    Email string
    Halls []Hall `gorm:"foreignKey:ActionID"`
}

type Hall struct {
    gorm.Model
    Name     string
    ActionID uint
    Stream   Stream  `gorm:"foreignKey:HallID"`
}

type Stream struct {
    ID     uint `gorm:"primaryKey"`
    HallID uint
    Name   string
}

db.Select("Halls").Delete(&action) - works fine for selected action and with all related halls.

How can I delete this one and related streams?
Something like:

db.Select("Halls", "Streams").Delete(&action)  
db.Select("Streams").Select("Halls").Delete(action)  

doesn't work.

Thanks

1 Answers
  • you can not use delete and select at same time in same query means it not feasible solution to do that but yeah you can use this reference link

  • Try Deleting action with where condition and specify HallID

db.Where("hall_id IN ?",HallID).Delete(&action)

and SET HallID to constraint:OnDelete:CASCADE in Stream so when you delete Halls then automatically Streams will be deleted whichever associated with that Halls

Related