Home > Backend Development > Golang > How to Efficiently Fetch Associated Data in GORM's Place-Town Relationship?

How to Efficiently Fetch Associated Data in GORM's Place-Town Relationship?

Linda Hamilton
Release: 2024-12-18 13:40:11
Original
887 people have browsed it

How to Efficiently Fetch Associated Data in GORM's Place-Town Relationship?

GORM Golang ORM Associations: Fetching Associated Fields

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
}
Copy after login

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)
}
Copy after login

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)
Copy after login

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}]
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template