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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With