Search code examples
gogo-gorm

Nested structs using gorm model


I have struct called User:

type User struct {
    Email string
    Name string
}

and struct called UserDALModel:

type UserDALModel struct {
    gorm.Model
    models.User
}

gorm Model looks like this:

type Model struct {
    ID        uint `gorm:"primary_key"`
    CreatedAt time.Time
    UpdatedAt time.Time
    DeletedAt *time.Time `sql:"index"`
}

this is possible to make UserDALModel nested with gorm model and user model so the output will be:

{
    ID
    CreatedAt
    UpdatedAt
    DeletedAt
    Email 
    Name
}

now the output is:

{
    Model: {
        ID
        CreatedAt
        UpdatedAt
        DeletedAt
    }
    User: {
        Name
        Email
    }
}

Solution

  • I found the answer:

    type UserModel struct {
        Email string
        Name string
    }
    
    type UserDALModel struct {
        gorm.Model
        *UserModal
    }
    
    ------------------------------
    
    user := UserModel{"name", "[email protected]"}
    userDALModel := UserDALModel{}
    userDal.UserModal = &user