GORM Zero-to-Many: Cannot add or update a child row: a foreign key constraint fails

Refresh

February 2019

Views

2 time

0

I am new to Golang and Gorm. I want to parse API response and store two tables. For each "reports" table, there can be zero-to-many tables of "personal_details".

However, gorm gave error when applying foreign key constraint because there's no record for PersonalDetail in API response sometimes.

I followed gorm docs and tried has-many relationship but i think it did not work for zero-to-many relationship

db.Model(&Report{}).AddForeignKey("personal_detail_id", "personal_details(id)", "RESTRICT", "RESTRICT")

type Report struct{
  gorm.Model
  PersonalDetail PersonalDetail `json:"PersonalDetail" gorm:"foreignkey:PersonalDetailId"`
  PersonalDetailId uint
}

type PersonalDetail struct{
  gorm.Model
  Name string `json:"Name"`
  Age string `json:"Age"`

0 answers