[英]Bigtable CellsColumnLimitFilter and ValueRangeFilter not working as intended
[英]On delete cascade not working as intended in Gorm
所以我對Gorm
很陌生並且正在玩它,但我似乎無法讓刪除級聯工作。 這些是我的模型:
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"`
}
問題是,當我對用戶 object 執行刪除操作時,它會被正確刪除,但關聯的Profile
object 不會被刪除。 我知道Gorm
具有軟刪除功能,但我的Base
model 中沒有gorm.DeletedAt
字段。 我的User
和Profile
model 也共享相同的Base
,因此它們在刪除方面的行為應該相似。
這是我運行刪除的方式:
...
id := "my-uuid" // this would be a real value. this is just an example
Database.Where("id = ?", id).Delete(&models.User{})
...
我究竟做錯了什么?
謝謝!
編輯:我知道這個問題並嘗試關注它,但我似乎無法讓它發揮作用。
如果您使用的是 gorm v2,您可以嘗試使用delete 和 select來刪除主要的 object、其關系和關聯對象。 它應該是這樣的:
Database.Select("Profile").Delete(&models.User{ID: id})
如果您的數據庫支持外鍵,您可以使用外鍵,否則您需要使用事務刪除用戶和配置文件 object。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.