如何预装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个回答



不幸的是,这只是GORM处理预加载的方式。</ p>

go-pg 的查询稍好一些,但功能与GORM不同。 在某些情况下,它仍然会执行多个查询。</ p>

老实说,我建议仅使用使用原始SQL构建查询,尤其是当您知道模型在编译时的外观时。 尽管我不知道我的模型看起来会是什么样,但最终我还是在项目中使用了这种方法。 </ p>
</ div>

展开原文

原文

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.

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐