Gorm insert into many to many not adding to join table

I have two tables: Meeting and Participant. A meeting can have multiple participants while a participant can take attend multiple meetings. This many2many relationship is structured in gorm as follow:

type Meeting struct {
    Id          uint   `json:"id" gorm:"primary_key"`
    MeetingName string `json:"meetingName" binding:"required"`
    Participants   []Participant  `json:"participants" gorm:"many2many:meeting_participants" binding:"required"`
}

type Participant struct {
    Id             uint           `json:"id" gorm:"primary_key"`
    Name           string         `json:"name" validate:"required"`
    Meetings       []Meeting      `json:"meetings" gorm:"many2many:meeting_participants"`
}

The issue is that when I add a new participant, gorm is not adding to the join table (meeting_participants). A new participant is added but the join table has no new record. The script to add participant is as follow:

func InsertParticipant(c *gin.Context) (string, error) {
    input, err := checkParticipantInput(c)
    if err != nil {
        return "", err
    }

    newParticipant := DB.Create(&input)
    DB.Save(&input)

    return input.Id, newParticipant.Error
}

func checkParticipantInput(c *gin.Context) (Participant, error) {
    var input Participant
    err := c.ShouldBindJSON(&input)
    if err != nil {
        return Participant{}, err
    }

    return input, err
}

Any idea what went wrong? Thanks in advance.



Read more here: https://stackoverflow.com/questions/67377505/gorm-insert-into-many-to-many-not-adding-to-join-table

Content Attribution

This content was originally published by jamfie at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: