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

How to query a many2many relationship with a Where clause on the association with go-gorm?

1个答案

1

When using the GORM ORM framework in Go for database operations, handling complex queries—especially those involving multiple association tables—can be achieved by constructing effective WHERE clauses in various ways. Here is one method for handling queries related to multiple associations:

Assume we have three models: User, Profile, and Address, where User has a one-to-one relationship with Profile, and User has a one-to-many relationship with Address. We need to query all users in a specific city with a particular hobby.

The model definitions are as follows:

go
package main import ( "gorm.io/driver/sqlite" "gorm.io/gorm" ) func main() { db, err := gorm.Open(sqlite.Open("test.db"), &gorm.Config{}) if err != nil { panic("failed to connect database") } var users []User db.Preload("Profile").Preload("Addresses"). Joins("JOIN profiles ON profiles.user_id = users.id"). Joins("JOIN addresses ON addresses.user_id = users.id"). Where("addresses.city = ? AND profiles.hobby = ?", "Shanghai", "Basketball"). Find(&users) // Output query results for _, user := range users { println(user.Name) } }

In this example, we first use Preload to preload the Profile and Addresses associations to ensure access to these data in subsequent operations. Then, we use the Joins method to connect the Profile and Address tables. The Where clause specifies the search conditions: users in "Shanghai" with the hobby "Basketball".

It is worth noting that this query approach may not be optimal in terms of performance, especially when dealing with large amounts of associated data. In practical applications, it may be necessary to adjust the query approach based on the specific database table structure and indexing strategy.

2024年8月12日 18:40 回复

你的答案