Reputation: 1273
Is there a way to tell gorm to select only those rows (Attractions), that have a hasOne relation (AttractionsData)? The same as I'd use "::has('relativeName)" in Laravel? The following code will return collection including Attractions with empty relation instead of skipping them
type Attractions struct {
ID uint `gorm:"primary_key"`
...
Active int `json:"-"`
AttractionsData AttractionsData `gorm:"foreignkey:AttractionID"`
}
type AttractionsData struct {
ID uint `gorm:"primary_key"`
AttractionID uint `json:"-"`
Lang string `json:"lang"`
Title string `json:"title"`
Active int `json:"-"`
}
...
func someFunc(c *gin.Context){
...
db := config.DBConnect()
defer db.Close()
var atts []Attractions
db.Preload("AttractionsData", "lang = ? AND active = ?", lang, 1).
Where("country_id = ?", countryID).
Where("category_id = ?", categoryID).
Where("active = ?", 1).
Find(&atts)
...
Upvotes: 1
Views: 642
Reputation: 1273
this code is seems to be working for me. Using LEFT JOIN and WHERE will filter unwanted Attractions. Although hoping to get a more elegant solution.
...
db.Joins("LEFT JOIN attractions_data ON attractions_data.attraction_id = attractions.id").
Preload("AttractionsData", "lang = ? AND active = ?", lang, 1).
Where("attractions.country_id = ?", countryID).
Where("attractions.category_id = ?", categoryID).
Where("attractions.active = ?", 1).
Where("attractions_data.active = ? AND attractions_data.lang = ?", 1,lang).
Find(&atts)
Upvotes: 0
Reputation: 64715
I would just get the ids you want first:
ids := []int{}
db.Model(&AttractionData{}).
Where("lang = ? AND active = ?", lang, 1).
Pluck("attraction_id", &ids)
db.Preload("AttractionsData").
Where("id IN (?)", ids).
Where("category_id = ?", categoryID).
Where("active = ?", 1).
Find(&atts)
Upvotes: 2