零对多:无法添加或更新子行:外键约束失败

I am new to Go 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"`

Try defining your models like this:

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

type PersonalDetail struct {
  gorm.Model
  Name string `json:"Name"`
  Age string `json:"Age"`
  ReportId uint `sql:"type:bigint REFERENCES reports(id) ON DELETE CASCADE"`
}

I've had some trouble getting foreign keys to work in GORM, so I've found using the SQL tag to define the relation seems to work better. It's not quite as clean since you need to define the actual database name rather than the field name, but it works.

Also keep in mind the order in which you migrate your tables. You may need to do it in an order, such that no tables that haven't yet been created yet aren't referenced. For this example, migrate Reports before PersonalDetail.