我正在尝试为仓库建模。现在我已经设置了我的东西,并且知道我想如何建模它,但我不知道如何使用 gorm 以正确的方式在这里选择东西。
我有以下类型:
type Store struct {
StoreID int `gorm:"primary_key;AUTO_INCREMENT;not null"`
Name string `gorm:"not null"`
Adress string `gorm:"not null"`
Manager User `gorm:"not null"`
ManagerID int `gorm:"foreignkey:ManagerID;not null"`
Boxes []Box `gorm:"foreignkey:StoreID;association_foreignkey:StoreID"`
}
type User struct {
UserID int `json:"id" gorm:"primary_key;AUTO_INCREMENT;not null"`
Username string `json:"username" gorm:"not null"`
Password string `json:"password" gorm:"not null"`
Email string `json:"email" gorm:"not null"`
Right UserRight `json:"userright" gorm:"not null"`
}
type Box struct {
BoxID int `gorm:"primary_key;AUTO_INCREMENT;not null"`
StoreID int `gorm:"not null"`
Code int `gorm:"type:integer(13)"`
Description string `gorm:"not null"`
}
现在,我想选择所有盒子,及其关联的商店以及所述商店的相关经理。 我是否必须使用联接来执行此操作,或者为此有更好的方法?
试试
boxes := []Box{}
db.Model(&Box{}).Preload("Store.Manager").Find(&boxes)