gorm omit id passed as it should not be casted during BindJson


(Tanweer Shahzaad) #1

I am using below structs and I dont want gorm to complain about id primary_key being duplicated. So I tried below approach to ignore the id field in create method. ie I have create another struct just for create and gorm is successfully ignoring value inside id passed. But I need to get id of newly created record. Which I though gorm will put in GetID but it didnt put any id in it.

Problem with above approach: I cant know the id of newly created record. if I knew somehow I would fetch that record in complete user struct and send back to user in response but its not happending.

Problem: I am trying to ignore id passed during create. There seems, two possible solutions: Either Gorm ignore id passed during create and return new id in the field. Or BindJson of gin context ignores the value and didnt bind it to user struct. Any help is really appreciated. Thanks

type UserBase struct {
  ID           uint `gorm:"primary_key"`
  Email        string `validate:"required,email"`
  Password     string
  LanguageId   int16
}

type UserCreateUpdate struct {
  UserBase
  ID           uint `gorm:"-",json:"id"`
  GetID           uint `gorm:"column:id",json:"id"`
  // Language language_schema.Language `json:",omitempty"`
}

type User struct {
  UserBase
  CreatedAt    time.Time
  UpdatedAt    *time.Time // As it can be null thats why the pointer
  Language language_schema.Language `json:",omitempty"`
}

// And this is create method
db := schema_utils.GetDB()

var user_create user_schema.UserCreateUpdate
c.BindJSON(&user_create)

validate := user_schema.SchemaValidator(web_api.GetValidator())
if ok, errors := schema_utils.ValidateInputs(user_create, validate); !ok {
  web_api.ValidationErrorResponse(errors, c)
} else {
  if result := db.Table("users").Create(&user_create); result.Error != nil {
    c.JSON(http.StatusUnprocessableEntity, gin.H{"error": result.Error})
  } else {
    var user user_schema.User
    fmt.Println("created")
    fmt.Println(user_create.ID)
    fmt.Println(user_create.GetID)
    db.Where("id = ?", user_create.GetID).Table("users").Preload("Language").First(&user)
    c.JSON(200, user)
  }
}