Your Question
I have the following nested structure (simplified for clarity; I'm not actually dealing with fruits): A main Fruit table with a reference to a FruitData table that holds additional data about each fruit, which in turn has an optional AppleData table which holds additional data specific to apples.
type Fruit struct {
gorm.Model
FruitData FruitData
FruitType int
}
type FruitData struct {
gorm.Model
FruitID uint
SourceCountry string
AppleData *AppleData
}
type AppleData struct {
gorm.Model
FruitDataID uint
Seeds int
}
I want to get a list of all apples with more than 4 seeds, while also preloading FruitData and FruitData.AppleData.
I could do it like this:
var fruits []Fruit
db.
Joins("JOIN fruit_datas ON fruit_datas.fruit_id = fruits.id").
Joins("JOIN apple_datas ON apple_datas.fruit_data_id = fruit_datas.id AND apple_datas.seeds > 4").
Preload("FruitData").
Preload("FruitData.AppleData").
Find(&fruits)
However, this requires doing both joins and preloading, which is wasteful. Is there any way to do the same thing without having to use both Joins and Preload for the same tables?
The document you expected this should be explained
https://gorm.io/docs/advanced_query.html https://gorm.io/docs/preload.html
Expected answer
An example on how to get the requested preloaded entries without unnecessary queries.
Comment From: github-actions[bot]
This issue has been automatically marked as stale because it has been open 360 days with no activity. Remove stale label or comment or this will be closed in 180 days
Comment From: saeidee
There are no unnecessary queries, the joins that you are using are part of the fetch Fruits query, and preloads are for preloading the relations.
With joins (3 queries)
Without joins (3 queries)