gogo-gormfibers

How do I store the data from DTO Gorm


I am using golang fiber and GORM. I am trying to store the data from DTO. For example, I have created a post entity and post dto like below.

type User struct {
    gorm.Model
    Name string
    Address string
    Phone string
}

This is my DTO

type PostDto struct {
    Name string `json:"name"`
    Address string `json:"address"`
    Phone string `json:"phone"`
}

I am trying to store the data like below

var postDto models.PostDto
c.BodyParser(&postDto)
err := database.DB.Model(models.User{}).Create(&postDto).Error
fmt.Println(err.Error())

But I am getting the below error

panic: reflect: call of reflect.Value.Field on string Value

Could anyone help to resolve this issue?

Thanks in advance


Solution

  • I don't know what you are doing? this is go language, not java, why do you define two structs?

    You can use tag to complete that you want.

    type User struct {
        gorm.Model `json:"-" gorm:"-"`
        Name string `json:"name" gorm:"column:name"`
        Address string `json:"address" gorm:"column:address"`
        Phone string `json:"phone"  gorm:"column:phone"`
    }
    
    
    var user User
    err := database.DB.Model(User{}).Create(&user).Error
    fmt.Println(err.Error())