go - 以正确的方式选择协会
问题描述
我正在尝试为仓库建模。现在我已经设置了我的东西并且知道我想如何建模它,但是我不知道如何使用 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"`
}
现在我想选择 All Boxes,以及它们关联的 Stores 以及与所述 Stores 关联的 Mangers。我是否必须通过加入来执行此操作,或者为此使用 gorm 更好的方法?
解决方案
尝试
boxes := []Box{}
db.Model(&Box{}).Preload("Store.Manager").Find(&boxes)
推荐阅读
- python - 如何使用 Pyside 实现交互式 QAction?(即如何在 QAction 中捕获事件?)
- python - 我想使用 for 循环以有组织的名称格式绘制多个文件的数据
- php - 什么会导致 PHP 表单 AddRecipient 出现错误 500?
- git - 无法使用 git clean -xdff 删除“.git”
- python - 使用 Selenium (Python) 自动登录
- html - 如何使用自定义安装的字体?
- vue.js - 通过单击文本更改状态?
- php - CKEditorType 在 symfony sonata admin 中显示文本区域
- android - 在 arm64 中设置硬件断点
- nginx - 如何将 URL/$directory 放入 NGINX 中的 rewrite url 参数中?