如何预装Gorm [英] How to preload with Gorm

查看:59
本文介绍了如何预装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)

也尝试过

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

预加载似乎是 select *实体,然后是使用 SELECT * FROM"repositories" INNER JOIN"entity_repositories" ON"entity_repositories"进行的内部联接."repository_id" =存储库." id"WHERE(" entity_repositories." entity_id"IN('1','2','3','4','5','6','7','8','9','10'))

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'))

随着用户数量的增加,由于达到了sqlite限制(dev),因此不再可维护.我尝试了许多排列!..实际上,我想我只希望它执行

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?

推荐答案

不幸的是,这只是GORM处理预加载的方式.

Unfortunately that's just the way GORM handles preloading.

go-pg 的查询略好,但功能与GORM.在某些情况下,它仍然会执行多个查询.

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

老实说,我建议仅对原始SQL使用查询构建如果您知道模型在编译时的外观.尽管我不知道我的模型看起来会是什么样,但最终我还是在项目中使用了这种方法.

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.

这篇关于如何预装Gorm的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆