Home >Backend Development >Golang >How to Efficiently Fetch Associated Data in GORM's Place-Town Relationship?
In GORM, a powerful ORM for Go, you can create associations between structs representing database tables. In this scenario, you have a Place struct associated with a Town struct, where each Place belongs to one Town.
Your code currently fetches all Place records, but you want to include the associated Town information for each Place. The error in your query is that the foreign key TownID is not specified in the Place struct.
To fix this, modify the Place struct:
type Place struct { ID int Name string TownID int // The foreign key Town Town }
Now, you have multiple options to retrieve the associated Town data:
Option 1: Manual Loading (Not Recommended)
Iterate over each Place and manually load the associated Town using Model.Related:
places := []Place{} db.Find(&places) for i, _ := range places { db.Model(places[i]).Related(&places[i].Town) }
This approach, while producing the expected result, suffers from the "N 1" problem, where multiple database queries are issued for each place.
Option 2: Preloading (Recommended)
Use the Preload function to eager load the associated Town while fetching Place records:
db.Preload("Town").Find(&places)
This will trigger only two queries: one to fetch all places and one to fetch all associated towns. It scales well with the number of places and towns.
Expected Output:
[{1 Place1 {1 Town1} 1} {2 Place2 {1 Town1} 1}]
The above is the detailed content of How to Efficiently Fetch Associated Data in GORM's Place-Town Relationship?. For more information, please follow other related articles on the PHP Chinese website!