10
votes

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
What do you have in mind? I general you could implement a query callback, but i don't think that worth the effort. Automatic Lazy loading is not possible, since there is no interception mechanism on the structs fields.0x434D53
Could you give a sample of the models? I'd kind of expect it to load those up without an explicit call to Preload so long as the relation is specified correctly. If not some option should be added to the package like CascadingRead that causes a recursive instantiation rather than returning me an object with empty arrays that should hold the many items my current object has foreign key relations with.evanmcdonnal

1 Answers

2
votes

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.