douyinjiao9351 2018-05-31 22:00
浏览 220

GORM递归预加载

Using Go 1.10, and CockroachDB via the Postgres pq driver.

I have a GORM model that looks like this:

type User struct {
    ID            string       `gorm:"type:UUID;primary_key;NOT_NULL"`
    UserName      string
    ... <other misc things here>
    EnclosedUsers []User    `gorm:"many2many:enclosed_user;jointable_foreignkey:parent_id;association_jointable_foreignkey:child_id"`
}

where ecnlosed_user is (specifically defined because reasons :) )

type EnclosedUsers struct {
    ParentID string `gorm:"type:UUID;default:'00000000-0000-0000-0000-000000000000'"`
    ChildID  string `gorm:"type:UUID;default:'00000000-0000-0000-0000-000000000000'"`
}

That is, each user can have 0 or many enclosed users, and each user may have many parent users. Im trying to preload all of the enclosed users for each user, however GORM only preloads the first level.

i.e.:

usr1
   |-> usr 2
   |     |->usr3
   |
   |-> usr4
         |->usr6

 usr5
   |->usr7

The only users that are loaded are usr1, usr2, usr4, usr5, and usr7. usr3 or usr 6 aren't. Im currently trying to recursively force the enclosed users to load with an AfterFind callback:

func (u *User) AfterFind(scope *gorm.Scope, role *CRRole) error {
    var childUsers []User

    if err := scope.DB().Model(&u).Related(&childUsers, "EnclosedUsers").Error; err != nil {
        return err
    }
    role.EnclosedRoles = childRoles

    return nil
}

However this generates the following SQL:

SELECT "users".* FROM "users" INNER JOIN "enclosed_users" ON "enclosed_users"."child_id" = "enclosed_users"."id" WHERE (user_name = 'test user 1') AND ("enclosed_users"."parent_id" IN ('<UUID HERE>')) 

if the user_name = ... wasn't there, the query would work perfectly.

Any ideas would be greatly appreciated.

  • 写回答

1条回答 默认 最新

  • donglou8371 2018-06-01 16:10
    关注

    I ended up forking the repository and removing callback_query_preload.go at line 331. Works like a charm.

    评论

报告相同问题?

悬赏问题

  • ¥15 2024-五一综合模拟赛
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭