GORM ManyToMany: Filter records by condition on manytomany association

Viewed 123

Consider below data structure:

type Foo struct {
 FooID   int64     `gorm:"primaryKey;column:foo_id"`
 FooBars []*FooBar `gorm:many2many:"foo_bar_map;foreignKey:foo_id;joinForeignKey:foo_id;references:bar_id;joinReferences:bar_id"`
}

type Bar struct {
 BarID   int64     `gorm:"primaryKey;column:bar_id"`
 FooBars []*FooBar `gorm:"many2many:foo_bar_map;foreignKey:bar_id;joinForeignKey:bar_id;references:foo_id;joinReferences:foo_id"`
}

type FooBarMap struct {
 FooID int64 `gorm:"primaryKey;column:foo_id"`
 BarID int64 `gorm:"primaryKey;column:bar_id;"`
 Foo   *Foo  `gorm:"foreignKey:foo_id;references:foo_id"`
 Bar   *Bar  `gorm:"foreignKey:bar_id;references:bar_id"`
}

Now the query I want to make is:

DB.Model(Foo{}).Preload("FooBars", "bar_id in ?", [1,2]).Find(&foos)

Basically I want to load only those Foos which are associated with Bar 1,2

this exact same query doesn't filter the records, because where condition becomes something like below:

  ...where bar_id in (1,2,3,4,5 ..all the mappings available) and bar_id in [1,2]

UPDATE

I've been able to solve this like below:

.Joins("INNER JOIN foo_bar_map on foo_bar_map.foo_id = foo.foo_id and foo_bar_map.foo_id in (?)", [1,2])

Is there a better way of creating this query, I am looking for ways to avoid using direct db column names in the code.

0 Answers
Related