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


February 2019


2 time


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{
  PersonalDetail PersonalDetail `json:"PersonalDetail" gorm:"foreignkey:PersonalDetailId"`
  PersonalDetailId uint

type PersonalDetail struct{
  Name string `json:"Name"`
  Age string `json:"Age"`

0 answers