Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to join multiple tables using GORM without Preload

Tags:

go

go-gorm

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.

like image 594
Metra Avatar asked Oct 16 '25 06:10

Metra


1 Answers

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)
like image 164
Emin Laletovic Avatar answered Oct 17 '25 22:10

Emin Laletovic



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!