问题答案 12026年7月4日 06:36
How to preload in gorm many to many with the condition in join table
In database operations with GORM, preloading is a commonly used technique, especially when handling many-to-many relationships. Preloading refers to loading related table data simultaneously with the main table query, which helps avoid subsequent N+1 query issues.Suppose we have a many-to-many relationship, such as User and Role, where they are linked through a join table, which we can call . Now, if we need to retrieve only users with specific roles, we can achieve this by combining GORM's method with a subquery.Below is a specific example demonstrating how to preload only the roles of users with the "Admin" role:In this example:We define two models and , and specify the many-to-many relationship using the tag.In the preloading section, we use the method. We specify the preloading conditions by using a subquery: only preload roles named "Admin".The subquery is used to filter role IDs where the role name is "Admin".Thus, when retrieving user information, only the roles with "Admin" will be loaded. This significantly reduces unnecessary data loading and improves query efficiency.