是否有一种方法告诉gorm仅选择具有hasOne关系(AttractionsData)的行(Attractions)?与在Laravel中使用“ :: has('relativeName)”相同吗?以下代码将返回包含具有空关系的景点的集合,而不是跳过它们
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)
...
答案 0 :(得分:2)
我只会先获取您想要的ID:
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)
答案 1 :(得分:0)
此代码似乎对我有用。使用LEFT JOIN和WHERE可以过滤掉不需要的景点。尽管希望得到一个更优雅的解决方案。
...
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)