Home > Net >  How to join multiple tables using GORM without Preload
How to join multiple tables using GORM without Preload

Time:03-07

I currently have 3 tables with relation between them through GORM. I'm looking to query the sellers with all informations about the relation. Here's my entities:

type ShopType struct {
    ID      uint       `gorm:"primarykey" json:"id"`
    Name    string     `json:"name" xml:"name" form:"name" query:"name"
}

type Shop struct {
    ID             uint       `gorm:"primarykey" json:"id"`
    Name           string     `json:"name" xml:"name" form:"name" query:"name"
    ShopType       ShopType   `gorm:"ShopTypeID;constraint:OnUpdate:CASCADE,OnDelete:RESTRICT;" json:"-"`
}


type Seller struct {
    ID           uint       `gorm:"primarykey" json:"id"`
    Firstname    string     `json:"firstname" xml:"firstname" form:"firstname" query:"firstname"
    Lastname     string     `json:"lastname" xml:"lastname" form:"lastname" query:"lastname"
    Shop         Shop       `gorm:"foreignKey:ShopID;constraint:OnUpdate:CASCADE,OnDelete:RESTRICT;" json:"-"`
}

It's not possible to use Joins instead of Preload like :

db.Model(&models.Seller{}).Joins("Shop").Joins("Shop.ShopType").Find(&results)

?

I have tried this but it doesn't work.

Also I have tried :

db.Model(&models.Seller{}).Joins("JOIN shops s on s.id = sellers.shop_id").Joins("JOIN shop_types st on st.id = s.shop_type_id")

It's work but it didn't fill the props of the Shop and ShopType entities, only the informations about the sellers are filled.

I'm looking to joins my entities using Joins instead of Preload because I want add some clauses to my query like : .Where('Shop.ShopType.Name IN (?)') and that's not possible with the Preload method.

CodePudding user response:

You are almost there with the second query, you can combine the Preload and Where functions with it.

var sellers []Seller 
db.Joins("JOIN shops s on s.id = sellers.shop_id").
       Joins("JOIN shop_types st on st.id = s.shop_type_id").
       Preload("Shop.ShopType").
       Where("st.name IN (?)", []string{"Store1", "Store2"}).
       Find(&sellers)
  • Related