Im new to Gorm. Im trying to do a cascade delete whereby if I delete a User, the Role (Belongs To), Profile (Has One) and Books (One-to-Many) which are associated with the User will be deleted as well.
I set up my model below but cascading can't seem to work. When I delete my User, the Role, Profile and Books still remain in the database rather than being deleted / soft deleted.
Can someone point me to where I did wrong? Thanks
User Model
type User struct {
gorm.Model
Name string `json:"name"`
Age uint `json:"age"`
Profile Profile `gorm:"constraint:OnDelete:CASCADE;"`
RoleID int `json:"role_id"`
Role Role `gorm:"constraint:OnDelete:CASCADE;"`
Books []Book `gorm:"constraint:OnDelete:CASCADE;"`
}
type Book struct {
gorm.Model
Title string `json:"title"`
UserID uint `json:"user_id"`
}
type Profile struct {
gorm.Model
Country string `json:"country"`
UserID uint `json:"user_id"`
}
type Role struct {
ID int
Name string `json:"name"`
}
When using gorm.Model
, or more specifically when your model has a field of type gorm.DeletedAt
, GORM uses soft delete. That is, records do not actually get deleted, only the aforementioned field gets updated, and the records are normally excluded from query results. Consequently, cascade delete will not trigger.
You can find, and then actually delete, soft-deleted objects using the Unscoped
method. Alternatively, change your models so that they are not affected by soft-deletion.