I am new to GORM and I am unable to understand how its working in background.
I have a table called user and user_type and I am trying to create a user.
type User struct {
// .... Some fields here
AccountId *uuid.UUID `json:"foreignid,omitempty" gorm:"column:account_id" immutable:"-"`
TypeIds []uuid.UUID `json:"typeids,omitempty" gorm:"-:all"`
Types []Type `json:"-" gorm:"many2many:user_type;"`
}
type Type struct {
// .... Some fields here
TypeIds []uuid.UUID `json:"typeids,omitempty" gorm:"-:all"`
Types []Type `json:"-" gorm:"many2many:type_on_type;foreignKey:id;joinForeignKey:type_id;References:id;joinReferences:inner_type_id"`
}
type UserType struct {
UserId *uuid.UUID `json:"user" gorm:"column:user_id" immutable:"-" validate:"required"`
TypeId *string `json:"type" gorm:"column:type_id"`
Type *string `json:"type" gorm:"column:type"`
}
func (rcv *User) Create(context *gin.Context, body []byte) (interface{}, *mn.Error) {
resourceSlice := reflect.New(reflect.MakeSlice(reflect.SliceOf(rcv.resourceType), 0, 0).Type())
if goErr := json.Unmarshal(body, resourceSlice.Interface()); goErr != nil {
return nil, mn.ErrorJSONUnmarshal.Clone(goErr.Error())
}
result := db.Create(resourceSlice.Elem().Interface())
if result.Error != nil {
return nil,result.Error
}
return resourceSlice.Elem().Interface(), nil
}
When Create() is called, it shows two queries running .
- INSERT INTO “data”.”user_type” (“user_id”,”type_id”)
- INSERT INTO “data”.”user” ()
I am trying to add one additional column description
in user_type
table. But unable to find out from where INSERT INTO "data"."user_type"
is executed.
Thank you
I created new struct UserType{} and doing like below.
db.Create(&rpg.UserType{
UserId: user[0].Id,
TypeId: &user[0].TypeIds[0],
Type: user[0].Type,
})
But this fails because of duplicate key constrains (as record was inserted earlier)
Can you please help me to identify how initial query was made on user_type and how can I add additional column in that query itself?
If we can not do in initial query then what am I missing in second query?
Thank you