Gorm Golang获取集合及其关联关系

huangapple go评论87阅读模式
英文:

Gorm Golang fetching a collection and its relationships

问题

最近我开始使用Golang,并决定尝试使用GORM作为ORM。它在大多数情况下运行得很好,但像大多数ORM一样,有时候它有一些限制。幸运的是,它与database/sql非常紧密地结合在一起,所以我可以轻松地进行自定义查询。

我想知道在gorm中是否有其他方法可以实现这个功能:
我有一个名为Companies的结构体,Companies与emails、addresses和phones之间是一对多的关系。我在gorm中使用以下代码来获取公司列表及其相应的信息。我使用了gorm的Preload函数。

db.DBAccess.
	Model(&companies).
	Count(&dbInfo.Count).
	Order("companies.id asc").
	Offset(offset).
	Limit(length).
	Preload("Addresses").
	Preload("Phones").
	Preload("Emails").
	Find(&companies)

这个方法完全正常工作。然而,我觉得可能还有其他方法可以在没有Preload函数的情况下实现这个功能。有什么想法吗?

英文:

I recently started using Golang and decided to give GORM a try as an ORM.
It works pretty well on most things, but as most ORMs are sometimes it's limited. Luckily it ties very well into database/sql so I can do custom queries easily.

I'm wondering if there is any other way to do this in gorm:
I have a struct Companies, Companies have one to many relationships w/ emails, addresses, and phones. I use the following code in gorm to pull a list of companies and their corresponding info. I use gorm's Preload function.

db.DBAccess.
	Model(&companies).
	Count(&dbInfo.Count).
	Order("companies.id asc").
	Offset(offset).
	Limit(length).
	Preload("Addresses").
	Preload("Phones").
	Preload("Emails").
	Find(&companies)

This works perfectly fine. However I feel like there is another way to accomplish this without the Preload function. Any ideas?

答案1

得分: 2

你可以稍后加载相关实体(仅在需要时),使用DB.Related,如文档所示:

// 用户有多个电子邮件
db.Model(&user).Related(&emails)
//// SELECT * FROM emails WHERE user_id = 111;
// user_id是外键,111是用户主键的值

// 指定外键
db.Model(&user).Related(&emails, "ProfileId")
//// SELECT * FROM emails WHERE profile_id = 111;
// profile_id是外键,111是用户主键的值

我在文档中没有看到其他方法。

英文:

You can load the related entities later (only when/if needed), using DB.Related as shown in the documentation :

// User has many emails
db.Model(&user).Related(&emails)
//// SELECT * FROM emails WHERE user_id = 111;
// user_id is the foreign key, 111 is user's primary key's value

// Specify the foreign key
db.Model(&user).Related(&emails, "ProfileId")
//// SELECT * FROM emails WHERE profile_id = 111;
// profile_id is the foreign key, 111 is user's primary key's value

I do not see another way in the documentation.

huangapple
  • 本文由 发表于 2015年3月21日 04:17:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/29175144.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定