首页 > 解决方案 > 以正确的方式选择协会

问题描述

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

标签: goassociationsgo-gorm

解决方案


尝试

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

推荐阅读