I am new to GORM and I am unable to understand how its working in background.
I have a tables 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())
}
kindTags = rcv.GetKindTags() // I have latest values of type column here
_ := tx.SetupJoinTable(&rpg.User{}, "Types", &UserTag{})
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 .
1. INSERT INTO "data"."user_type" ("user_id","type_id")
2. INSERT INTO "data"."user" ()
I am trying to add one additional column type
in user_type
table.
For that I added a hook
func (ut *UserType) BeforeCreate(db *gorm.DB) error {
db.Statement.SetColumn("type", ut.Type) // need updated value here
return nil
}
After this I can see type
column getting added in query but value is null.
INSERT INTO “user_type” (“user_id”,“type_id”,“type”) VALUES (‘3091a78e-5a3c-6ae2-f36b-a9af1aa3982b’,‘ed31a1ce-8805-62fb-e7bf-fb751d6beb73’,NULL) ON CONFLICT DO NOTHING
But I am not able to populate updated value for ut.Type
using kindTags
which has column values.
Can you please tell me how can I pass the value to hook
?
Thank you