How to permanently delete associations in GORM

Viewed 137

I want to know how to permanently delete associations in GORM. I tried all examples shown in the documentation but I cannot get associations to become permanently deleted. For example, I am confused by GORM's documentation on deleting and clearing associations, which explicitly says: won't delete those objects from DB. (I don't understand what it means to delete objects without deleting them from the database.)

I have similar structs:

type User struct {
    gorm.Model
    City    string `sql:"type:varchar(255);not null"`
    Cards   []Card `gorm:"foreignKey:UserID;constraint:OnDelete:CASCADE"`
}

type Card struct {
    ID      uint   `gorm:"primary_key"`
    UserID  uint   `gorm:"column:user_id"`
}

I want to execute the following SQL query in GORM form:

DELETE c
FROM cards c
JOIN users u ON c.user_id = u.id
WHERE u.name = `Madrid`
1 Answers

gorm.Model is including a DeletedAt field. So on deletion, this will be set to the current date, the record won't be removed from the database, but will not be findable with normal query methods. They call that "soft delete".

In order to delete the record permanently you have to use Unscoped, like:

db.Unscoped().Delete(&order)

Source: https://gorm.io/docs/delete.html

Related