Your Question
Not sure if I'm missing something here.
We spend time defining associations (many-to-many, etc.). I'm assuming Gorm now knows how the models associate with one another.
I'm trying to build a query like so - get the values of some table A based on some values in table B after joining:
select * from distributions
inner join distributions_places dp on distributions.id=dp.distribution_id
inner join places p on places.id=dp.place_id
where places.some_field=some_value
I have my association set up:
type Place struct {
ID uint64 `gorm:"primaryKey;uniqueIndex;not null"`
Distributions []Distribution `gorm:"many2many:distribution_places;"`
SomeField string
}
type Distribution struct {
ID []byte `gorm:"type:bytea;primaryKey;uniqueIndex;not null"`
Places []Place `gorm:"many2many:distribution_places;"`
}
However, I can't find a way to leverage this information to generate my query. There are joins, but this requires manually specifying the join condition (which my association should render unnecessary). There's also Associations, but this doesn't work:
var distributions []db_models.Distribution
places := []db_models.Place{
{SomeField: "some_value"},
}
err = db.Debug().Model(places).Association("Distributions").Find(&distributions)
...because this runs into https://github.com/go-gorm/gorm/issues/6369 . From my understanding, Association Mode only works if you already have the IDs you're looking for in the associated table.
The document you expected this should be explained
https://gorm.io/docs/query.html#Joins
Expected answer
What's the right way to accomplish this? It seems pretty basic, but the docs aren't helpful.
Comment From: dorner
It looks like this has come up in the past: #3287 and #4601. This seems like an obvious and basic use case. Are there plans to support this?
Comment From: YuZongYangHi
After such a comparison, I suddenly feel that beego orm is much easier to use, at least you can use table1__table2_filed to query in relational queries
Comment From: saeidee
Related to https://github.com/go-gorm/gorm/issues/3287, https://github.com/go-gorm/gorm/issues/4601.
Feel free to open a feature request with a good usecase example.