Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Gorm Golang fetching a collection and its relationships

Tags:

orm

go

go-gorm

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?

like image 563
user1943442 Avatar asked Mar 20 '15 20:03

user1943442


1 Answers

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.

like image 119
HectorJ Avatar answered Nov 05 '22 15:11

HectorJ