英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论