GORM Many to many add additional column

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

change like this :

kindTags := rcv.GetKindTags() // Fetch kindTags here

    // Assuming kindTags is a map or has some structure to get the Type value
    // Setup the join table
    _ = tx.SetupJoinTable(&User{}, "Types", &UserType{})

    // Use the resourceSlice to set up user and types
    users := resourceSlice.Elem().Interface().([]User)
    for i := range users {
        for j := range users[i].Types {
            users[i].Types[j].Type = kindTags[users[i].Types[j].TypeId] // Or however you get the value
        }
    }

func (ut *UserType) BeforeCreate(tx *gorm.DB) error {
    // Set the Type value here based on some logic
    // For example, if kindTags is available in context or a global variable
    ut.Type = "someValueFromKindTags" // Replace this with the actual logic to get kindTags value
    return nil
}

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.