I have two tables: Meeting and Participant . A meeting can have multiple participants while a participant can 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
}
Json input:
{
"name":"testParticipant",
"meetings": [{"id": 40}]
}
Any idea what went wrong? Thanks in advance.
I have two tables: Meeting and Participant . A meeting can have multiple participants while a participant can 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.
Not so sure why but I restarted my server and it works. Perhaps something to do with automigrate not working when the server hot reloads.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.