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

How to retrieve parent table using child table in Gorm

1个答案

1

When performing database operations with Gorm, we often need to handle relationships between models. If you need to retrieve parent table information through the child table, you can use Gorm's preloading feature to achieve this. I'll illustrate this operation with a concrete example.

Assume we have two models, User and Profile, where Profile is the child table of User. User is the parent table containing basic user information, while Profile stores detailed user information.

go
type User struct { ID uint Name string Profile Profile } type Profile struct { ID uint UserID uint Address string Phone string }

In the above models, Profile is associated with the User model through the UserID field.

Step 1: Configure the database and migration

First, ensure that Gorm and the database connection are properly configured. Then, use Gorm's auto-migration feature to create or update the tables in the database:

go
db, err := gorm.Open(sqlite.Open("test.db"), &gorm.Config{}) if err != nil { panic("failed to connect database") } // Migrate schema db.AutoMigrate(&User{}, &Profile{})

Step 2: Insert data

Before retrieving data, we need to insert some sample data into the database:

go
user := User{Name: "John Doe"} profile := Profile{Address: "123 Main St", Phone: "123-456-7890"} user.Profile = profile db.Create(&user)

Step 3: Use preloading to retrieve data

Now, if we want to retrieve parent table User data based on child table Profile information, we can use preloading. There are two methods to achieve this:

Method 1: Preload the parent table

If we know the specific Profile ID and wish to retrieve the associated User information:

go
var profile Profile db.Preload("User").First(&profile, "id = ?", profileID) fmt.Println(profile.User.Name)

Method 2: Query the parent table using child table conditions

If we want to find the user with phone number "123-456-7890":

go
var user User db.Joins("Profile").Where("profiles.phone = ?", "123-456-7890").First(&user) fmt.Println(user.Name)

In this example, the Joins method is used to join the Profile table, and the Where method specifies the search conditions. This method is particularly suitable for scenarios where you need to find parent table records based on specific field values in the child table.

This covers the basic methods for retrieving parent tables using child tables in Gorm. These techniques are very practical, especially when dealing with large databases that have complex relationships.

2024年8月12日 17:17 回复

你的答案