Search code examples
gogo-gorm

GORM embedded struct not working correctly


I receive this error

controllers/users.go:61:36: user.ID undefined (type models.User has no field or method ID)

when using

var user models.User

...

jwtToken, err := generateJWT(user.ID, user.Username)

The definition of User model:

package models

import "time"

type BaseModel struct {
    ID        uint `json:"id" gorm:"primaryKey"`
    CreatedAt time.Time
    UpdatedAt time.Time
}

type User struct {
    BaseModel BaseModel `gorm:"embedded"`
    Username  string    `json:"username"`
    Password  string    `json:"password"`
}

Actually I put BaseModel in different file but in the same package with User. Migration works fine as table users have all columns in BaseModel. What is the problem? I use golang 1.18 and latest version of GORM


Solution

  • You have used BaseModel as attribute in your model so even though gorm can very well map it to the table column to access it, you have to use the attribute name

    To access you would do

    jwtToken, err := generateJWT(user.BaseModel.ID, user.Username)
    

    you could also try this next code to see if it works otherwise the above will work for sure

    type BaseModel struct {
        ID        uint `json:"id" gorm:"primaryKey"`
        CreatedAt time.Time
        UpdatedAt time.Time
    }
    
    type User struct {
        BaseModel `gorm:"embedded"`
        Username  string    `json:"username"`
        Password  string    `json:"password"`
    }
    

    now you might be able to access it like your original pattern

    jwtToken, err := generateJWT(user.ID, user.Username)