I'm using gorm and postgresql for a side-project, and I don't know how to solve this problem in 1 request:
My User type is the following:
type User struct {
UserId string
Email string
FirstName string
LastName string
Phone string
Address_1 string
Address_2 string
City string
State string
Zip string
Gender string
ImageUri string
Roles []Role `gorm:"foreignkey:UserId"`
}
My Role type is the following:
type Role struct {
UserId string
Role string
}
I want to get all users with their associated roles, but right now i'm doing this with 2 requests and I want to do it only with one:
func (s *Store) ListUsers() ([]User, error) {
users := []User{}
if err := db.Joins("join roles ON roles.user_id = users.user_id").Find(&users).Error; err != nil {
return nil, err
}
for i, user := range users {
roles := []Role{}
if err := db.Where("user_id = ?", user.UserId).Model(&Role{}).Find(&roles).Error; err != nil {
return User{}, errors.Wrap(err, "failed to get roles")
}
users[i].Roles = roles
}
return users, nil
}
I tried with several different requests, using Related
etc... but my Roles slice is always empty. Any ideas ?
[EDIT] My sql schema
CREATE TABLE IF NOT EXISTS users (
user_id varchar PRIMARY KEY UNIQUE NOT NULL,
email varchar UNIQUE NOT NULL,
first_name varchar,
last_name varchar,
phone varchar,
address_1 varchar,
address_2 varchar,
city varchar,
state varchar,
zip varchar,
gender varchar,
image_uri varchar
);
CREATE TABLE IF NOT EXISTS roles (
user_id varchar REFERENCES users (user_id) ON DELETE CASCADE,
role varchar NOT NULL
);
There @har07 soultions it's probably what you need db.Preload("Roles").Find(&users)
but you can't get Roles
because you don't have primary key
declared in you user struct
, so at the end your user should look like this:
type User struct {
UserId string `gorm:"primary_key"`
Email string
FirstName string
LastName string
Phone string
Address_1 string
Address_2 string
City string
State string
Zip string
Gender string
ImageUri string
Roles []Role `gorm:"foreignkey:UserId"`
}