1

I'm trying to model a warehouse. Now I have my stuff setup and know how I want to model it, but I don't know how to select stuff here the right way with gorm.

I have the following types:

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"`
}

Now I'd like to select All Boxes, with their associated Stores aswell as the associated Mangers to said Stores. Do I have to do this with a join or has gorm a nicer method for this?

PhilmacFLy
  • 21
  • 5
  • take a look at http://gorm.io/docs/preload.html – thesyncim Aug 21 '18 at 14:51
  • I read the whole documentation multiple times, believe me, I didn't manage to do it, otherwise I wouldnt be asking – PhilmacFLy Aug 21 '18 at 16:40
  • set debug option to see the generated query. this looks like a dup (https://stackoverflow.com/questions/29230261/how-preload-a-full-hierarchy-in-go-using-gorm). hope that helps – thesyncim Aug 21 '18 at 20:25
  • Not really the only thing im getting out of it now is `Error fetching Boxes: can't preload field store_id for db100.Box`. Furthermore I dont think its a dub, as I want to load the parents, not the Childern. I want to get a list of all Boxes with the Store they are in as well as the Stores Manager. – PhilmacFLy Aug 22 '18 at 07:29

1 Answers1

0

try

boxes := []Box{}
db.Model(&Box{}).Preload("Store.Manager").Find(&boxes)
RuNpiXelruN
  • 1,850
  • 2
  • 17
  • 23