Multiple Create with User ID as foreign key not working

I have an api for multiple creation of user call logs. The problem i have is in having the UserID to be included in the CreateInBatches

My API payload is as below


I want the logged person to be able to save this data at once.

Below is my struct

type UserCallLog struct {
	ID                  uuid.UUID `gorm:"type:uuid;default:uuid_generate_v4();primaryKey"`
	FormattedNumber     string    `json:"formatted_number"  gorm:"type:varchar(255);index"`
	CachedMatchedNumber string    `json:"cached_matched_number"  gorm:"type:varchar(255);index"`
	UserID              uuid.UUID `json:"user_id" binding:"omitempty,uuid4" gorm:"index"`
	User                User      `gorm:"foreignKey:UserID;references:ID"`
	CreatedAt time.Time
	UpdatedAt time.Time

Kindly help me know what the problem in my code as below

func CreateCallLogs(c *gin.Context) {
	user_id, _ := c.Get("id")
	var callmetrics []models.UserCallLogMetric
	var err []string
	jsonError := c.ShouldBindJSON(&callmetrics)
	if jsonError != nil {
		err = append(err, utilities.Validate(jsonError)...)
		utilities.ShowError(c, http.StatusBadRequest, err)
	callmetrics.UserID = user_id.(uuid.UUID)
	result :=database.DB.CreateInBatches(callmetrics, 100)
	if result.Error != nil {
		err = append(err, result.Error.Error())
		utilities.ShowError(c, http.StatusBadRequest, err)
	utilities.ShowMessage(c, http.StatusOK, "call logs created successfully")

I will greatly appreciate the help

Can you be more specific about what the problem is? Looking at your code, it looks to me like it won’t compile because var callmetrics []models.UserCallLogMetric defines callmetrics as a slice, but then you’re trying to set a field on it here: callmetrics.UserID = user_id.(uuid.UUID) If your problem is that it won’t compile, it looks to me like you have to loop through the structs in callmetrics and set the UserID field on each one. If that’s not the problem, we need more information.

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