Objective: If a User is marked deleted in a soft delete, his calendar should also be marked deleted.
structs:
type User struct {
gorm.Model
Username string
FirstName string
LastName string
Calendar Calendar
}
type Calendar struct {
gorm.Model
Name string
UserID uint
}
constraint:
db.Model(&Calendar{}).AddForeignKey("user_id", "users(id)", "CASCADE","CASCADE")
Problem:
A hard delete works: Both the user and his calendar are deleted (records are gone)
db.Exec("Delete from users where id=3")
A soft delete does not work as anticpated:
db.Where("id = ?", 3).Delete(&User{})
With a soft delete,
Any ideas?
A soft delete means gorm do not remove your data. It only mark a non-zero DeleteAt
timestamp. That is not supported by database directly. So foreign key has no effect here.
That means you need to manually implement the cascaded delete yourself, like this:
func DeleteUser(db *gorm.DB, id int) error {
tx := db.Begin()
if tx.Where("id = ?", id).Delete(&User{}); tx.Error != nil {
tx.Rollback()
return tx.Error
}
// Changed this line
// if tx.Where("user_id = id", 3).Delete(&Calendar{}); tx.Error != nil {
if tx.Where("user_id = ?", id).Delete(&Calendar{}); tx.Error != nil {
tx.Rollback()
return tx.Error
}
return tx.Commit().Error
}