go-gorm / gorm.io

GORM official site

Home Page:https://gorm.io

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

[Question] M:M Custom Join Table | Fetching data

JairDavid opened this issue · comments

Document Link

ManyToMany Relationship

Your Question

Hi, I am trying to create an M:M relationship with a custom join table, I basically followed the documentation, the table is created successfully with its relationship and fields, but when I try to get the data it doesn't work. I'm not sure if I'm missing something but here's the code and what I expected

type User struct {
	ID             uint `gorm:"primaryKey"`
	Email          string `gorm:"type:varchar(30);unique;not null"`
	Password       string `gorm:"type:varchar(80);not null"`
	Roles          []Role `gorm:"many2many:user_roles;"`
	CreatedAt      time.Time
	UpdatedAt      time.Time
}

type UserRole struct {
	UserID uint `gorm:"primaryKey"`
	RoleID     uint `gorm:"primaryKey"`
}

type Role struct {
	ID          uint   `gorm:"primaryKey"`
	RoleName    string `gorm:"type:varchar(30);not null"`
	Description string `gorm:"type:varchar(50);not null"`
}

//Adding config for migration
err := Database.SetupJoinTable(&models.User{}, "Roles", &models.UserRole{})

//Query
if err := r.database.Model(&domain.User{}).Where("email = ?", loginCredentials.Email).Preload("Roles").Find(&employee).Error; err != nil {
return nil, errors.New(ERROR_PROCCESS)
}
.....

image

Expected answer

An User struct/response with their roles (I am working with a rest api) (something like: )

		"id": 1,
		"email": "manuel@gmail.com",
		"password": "$2a$04$9n/mJF/iRfkwGGa/l72hxuspQX7jiuIadXzWEbpLIZwfDVJn0/JOi",
                "roles":[
                       {
                          "id":1,
                          "role_name":"ROLE_EMPLOYEE",
                          "more_flieds":"......"
                        }
                 ]
		"CreatedAt": "2022-06-11T17:45:09.7364774-05:00",
		"UpdatedAt": "2022-06-11T17:45:09.7364774-05:00"