dtdvbf37193 2019-01-02 18:55
浏览 38
已采纳

如何预装Gorm

I am hitting a road block with preloading and associations

type Entity struct {
  ID           uint `gorm:"primary_key"`
  Username     string
  Repositories []*Repository `gorm:"many2many:entity_repositories"`
}

type Repository struct {
  ID       uint `gorm:"primary_key"`
  Name     string
  Entities []*Entity `gorm:"many2many:entity_repositories"`
} 

With small users numbers the preloading is fine using the below

 db.Preload("Repositories").Find(&list)

Also tried

 db.Model(&User{}).Related(&Repository{}, "Repositories").Find(&list)

The preload seems to a select * entities and then a inner join using a SELECT * FROM "repositories" INNER JOIN "entity_repositories" ON "entity_repositories"."repository_id" = "repositories"."id" WHERE ("entity_repositories"."entity_id" IN ('1','2','3','4','5','6','7','8','9','10'))

As the number of user's increases this is no longer maintainable as it hits a sqlite limit (dev). I've tried numerous permutations! .. Realistically i guess i just want it to do something like

SELECT entities.*, repositories.*  
FROM entities 
JOIN entity_repositories ON entity_repositories.entity_id = entities.id
JOIN repositories ON repositories.id = entity_repositories.repository_id
ORDER BY entities.id

And fill in the model for me ..

Am I doing something obviously wrong or?

  • 写回答

1条回答

  • duanqu9279 2019-01-02 22:54
    关注

    Unfortunately that's just the way GORM handles preloading.

    go-pg has slightly better queries, but doesn't have the same functionality as GORM. It still will do multiple queries in some cases.

    I would honestly recommend just using query building with raw SQL, especially if you know what your models will look like at compile time. I ended up going with this approach in my project, despite the fact that I didn't know that my models were going to look like.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 maixpy训练模型,模型训练好了以后,开发板通电会报错,不知道是什么问题
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 有没有帮写代码做实验仿真的
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥30 vmware exsi重置后登不上
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容