1 回答

TA貢獻1874條經驗 獲得超12個贊
第一點是因為您正在使用自定義主鍵,所以您不應該使用它
gorm.Model
,因為它包含ID
字段。參考第二點根據你的描述,
store
(location) 和 是一對多的關系drink
。這意味著一家商店可以有多種飲料,但一種飲料應該只屬于一家商店。在one-to-many
關系中,旁邊應該有一個參考或關系 IDmany
。這意味著你在drink
表中的情況。那么你的結構應該是這樣的:
我的模型結構
type MyModel struct {
CreatedAt time.Time
UpdatedAt time.Time
DeletedAt gorm.DeletedAt `gorm:"index"`
}
位置結構(商店)
type Location struct {
MyModel
ID uuid.UUID `gorm:"primary key;type:uuid"`
// other columns...
Drinks []Drink
}
飲料結構
type Drink struct {
MyModel
ID uuid.UUID `gorm:"type:uuid;primary key"`
//other columns...
LocationID uuid.UUID// This is important
}
然后gorm會自動考慮drink
表中的 LocationID 將引用位置表的 ID 字段。您還可以在 Location 結構的 Drinks 數組字段中明確指示它使用 gorm gorm:"foreignKey:LocationID;references:ID"
。
- 1 回答
- 0 關注
- 126 瀏覽
添加回答
舉報