10

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?

4

1 回答 1

2

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

// 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

我在文档中看不到另一种方式。

于 2015-09-04T14:29:07.210 回答