乐闻世界logo
搜索文章和话题

How to get double nested data with gorm?

1个答案

1

How to Retrieve Double-Nested Data with GORM?

When working with GORM for data operations, handling double-nested data structures is a common requirement. This typically involves two or more levels of associated models. The following outlines the steps and examples for retrieving double-nested data using GORM:

Defining Data Models

First, we need to define the relevant data models. Suppose we have three models: User, Profile, and Address, where Profile is a sub-model of User, and Address is a sub-model of Profile.

go
type User struct { gorm.Model Name string Profile Profile } type Profile struct { gorm.Model UserID uint Bio string Address Address } type Address struct { gorm.Model ProfileID uint Street string City string }

Using Preload for Queries

Using GORM's Preload method, we can load related association data in a single query. To load User along with its Profile and the Address of Profile, you can do the following:

go
var users []User db.Preload("Profile.Address").Find(&users)

This code first retrieves the User data, then preloads the Profile for each User, and the Address for each Profile. Using the Preload approach effectively reduces the number of database queries, as it retrieves as much related data as possible in the fewest queries.

Handling Complex Queries

If the query requires more complex filtering conditions, you can use the Where clause within Preload for more precise data loading:

go
var users []User db.Preload("Profile", "profiles.deleted_at IS NULL").Preload("Profile.Address", "addresses.city = ?", "New York").Find(&users)

Here, we add a condition for undeleted profiles when loading Profile, and specify the city as 'New York' when loading Address.

Summary

By using GORM's Preload method, we can effectively and conveniently load double-nested or more deeply nested association data. This not only reduces code complexity but also optimizes application performance. In practical development, choosing appropriate preloading strategies and conditions based on specific business requirements can better leverage the advantages of ORM tools.

2024年8月12日 18:31 回复

你的答案