[英]On delete cascade not working as intended in Gorm
So I am very new to Gorm
and am playing around with it but I can't seem to get on delete cascade to work.所以我对
Gorm
很陌生并且正在玩它,但我似乎无法让删除级联工作。 These are my models:这些是我的模型:
type Base struct {
Id string `json:"id" gorm:"type:uuid;primary_key"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
type User struct {
Base
Role string `json:"role"`
Username string `json:"username" gorm:"unique"`
Password string `json:"password"`
Profile Profile `gorm:"constraint:OnDelete:CASCADE;"`
}
type Profile struct {
Base
UserId string `json:"user_id"`
Name string `json:"name"`
Bio string `json:"bio" gorm:"default:hello world!"`
Age uint8 `json:"age"`
}
The problem is, when I perform a delete operation on a user object, it gets deleted properly but it's associated Profile
object isn't deleted.问题是,当我对用户 object 执行删除操作时,它会被正确删除,但关联的
Profile
object 不会被删除。 I know that Gorm
has a soft delete functionality but I don't have a gorm.DeletedAt
field in my Base
model.我知道
Gorm
具有软删除功能,但我的Base
model 中没有gorm.DeletedAt
字段。 My User
and Profile
model also share the same Base
so they should behave similarly in terms of the delete.我的
User
和Profile
model 也共享相同的Base
,因此它们在删除方面的行为应该相似。
Here's how I am running the delete:这是我运行删除的方式:
...
id := "my-uuid" // this would be a real value. this is just an example
Database.Where("id = ?", id).Delete(&models.User{})
...
What am I doing wrong?我究竟做错了什么?
Thank you!谢谢!
Edit: I am aware of this question and have tried following it but I can't seem to get this to work.编辑:我知道这个问题并尝试关注它,但我似乎无法让它发挥作用。
If you are using gorm v2, you can try deleting the main object, its relation, and the associated objects by using delete with select .如果您使用的是 gorm v2,您可以尝试使用delete 和 select来删除主要的 object、其关系和关联对象。 It should be something like this:
它应该是这样的:
Database.Select("Profile").Delete(&models.User{ID: id})
you could use foreign key if your database support foreign key, if not you need use transaction to deleted the user and profile object.如果您的数据库支持外键,您可以使用外键,否则您需要使用事务删除用户和配置文件 object。
https://gorm.io/docs/transactions.html
https://gorm.io/docs/transactions.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.