From c575a4e71922f7eb1c892e12eb23a0cab4adccd2 Mon Sep 17 00:00:00 2001 From: ruozhixian Date: Thu, 11 Mar 2021 16:36:49 +0800 Subject: [PATCH] support to preload all children in multiple levels associations --- callbacks/query.go | 24 +++++++++++++++++++----- 1 file changed, 19 insertions(+), 5 deletions(-) diff --git a/callbacks/query.go b/callbacks/query.go index 1868c247..df5b4d60 100644 --- a/callbacks/query.go +++ b/callbacks/query.go @@ -185,12 +185,26 @@ func Preload(db *gorm.DB) { } } else { preloadFields := strings.Split(name, ".") - if _, ok := preloadMap[preloadFields[0]]; !ok { - preloadMap[preloadFields[0]] = map[string][]interface{}{} - } + if preloadFields[0] == clause.Associations { + for _, rel := range db.Statement.Schema.Relationships.Relations { + if rel.Schema == db.Statement.Schema { + if _, ok := preloadMap[rel.Name]; !ok { + preloadMap[rel.Name] = map[string][]interface{}{} + } - if value := strings.TrimPrefix(strings.TrimPrefix(name, preloadFields[0]), "."); value != "" { - preloadMap[preloadFields[0]][value] = db.Statement.Preloads[name] + if value := strings.TrimPrefix(strings.TrimPrefix(name, preloadFields[0]), "."); value != "" { + preloadMap[rel.Name][value] = db.Statement.Preloads[name] + } + } + } + } else { + if _, ok := preloadMap[preloadFields[0]]; !ok { + preloadMap[preloadFields[0]] = map[string][]interface{}{} + } + + if value := strings.TrimPrefix(strings.TrimPrefix(name, preloadFields[0]), "."); value != "" { + preloadMap[preloadFields[0]][value] = db.Statement.Preloads[name] + } } } }