简体   繁体   English

如何预加载 Gorm

[英]How to preload with 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'))预加载似乎是select * entities ,然后使用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).随着用户数量的增加,这不再可维护,因为它达到了 sqlite 限制(开发)。 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?我是不是在做一些明显错误的事情?

Unfortunately that's just the way GORM handles preloading.不幸的是,这只是 GORM 处理预加载的方式。

go-pg has slightly better queries, but doesn't have the same functionality as GORM. go-pg有更好的查询,但没有 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.老实说,我建议只使用带有原始 SQL 的查询构建,特别是如果您知道模型在编译时的样子。 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.我最终在我的项目中采用了这种方法,尽管我不知道我的模型会是什么样子。

可以试试Joins() ,它可以在 SQL 中执行 JOIN 语法

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM