如何在GORM中永久删除关联关系

huangapple go评论81阅读模式
英文:

How to permanently delete associations in GORM

问题

我想知道如何在GORM中永久删除关联。我尝试了文档中显示的所有示例,但无法使关联被永久删除。例如,我对GORM关于删除和清除关联的文档感到困惑,文档明确表示:不会从数据库中删除这些对象(我不明白删除对象而不从数据库中删除它们是什么意思)。

我有类似的结构体:

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"`
}

我想在GORM中执行以下SQL查询:

DELETE c
FROM cards c
JOIN users u ON c.user_id = u.id
WHERE u.name = 'Madrid'
英文:

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

得分: 5

gorm.Model 包含一个 DeletedAt 字段。因此,在删除时,该字段将被设置为当前日期,记录不会从数据库中删除,但无法使用普通的查询方法找到。他们称之为“软删除”。

要永久删除记录,您需要使用 Unscoped,例如:

db.Unscoped().Delete(&order)

来源:https://gorm.io/docs/delete.html

英文:

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

huangapple
  • 本文由 发表于 2022年6月26日 23:29:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/72762884.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定