【问题标题】:Selecting Associations the right way以正确的方式选择协会
【发布时间】:2019-01-27 16:35:55
【问题描述】:

我正在尝试为仓库建模。现在我已经设置好我的东西并且知道我想如何建模它,但我不知道如何使用 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"`
}

现在我想选择所有盒子及其关联的商店以及与所述商店关联的经理。 我是否必须通过 join 来执行此操作,或者为此使用 gorm 更好的方法?

【问题讨论】:

  • 我多次阅读整个文档,相信我,我没能做到,否则我不会问
  • 设置调试选项以查看生成的查询。这看起来像一个 dup (stackoverflow.com/questions/29230261/…)。希望有帮助
  • 不是我现在唯一能摆脱的就是Error fetching Boxes: can't preload field store_id for db100.Box。此外,我不认为它是配音,因为我想加载父母,而不是孩子。我想获取所有 Box 的列表,其中包含它们所在的 Store 以及 Stores Manager。

标签: go associations go-gorm


【解决方案1】:

试试

boxes := []Box{}
db.Model(&Box{}).Preload("Store.Manager").Find(&boxes)

【讨论】:

    猜你喜欢
    • 2014-03-30
    • 2019-06-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-06
    • 1970-01-01
    • 2016-11-13
    • 1970-01-01
    相关资源
    最近更新 更多