Foreign key constraint fail in recursive table

I am trying to add a foreign key in recursive Table and enable onDelete onUpdate CASCADE mode to delete all children when parent is deleted (same with update)

package main

import (
  "github.com/jinzhu/gorm"
  _ "github.com/jinzhu/gorm/dialects/mysql"
)

type User struct {
  gorm.Model
  Name string 
  Child   *User `gorm:"Foreignkey:Parent"` 
  Parent uint
}
  
func main() {
  db, err := gorm.Open("mysql", "root@/testdb")
  if err != nil {
    panic("failed to connect database")
  }
  defer db.Close()
 
  // Migrate the schema
  db.AutoMigrate(&User{})
  db.Model(&User{}).AddForeignKey("parent","users(id)","CASCADE","CASCADE")

  // Create
  u := User{Name: "Parent", Child: &User{Name:"Child"}}  
  db.Save(&u)
  
}

Error message

Hi. Just some ideas. Does it work if you add the child first and then the parent? Or the other way around? The constraint would fail if the child is added first then the parent don’t exist in the database. Can you make gorm output all sql it generates with

db.LogMode(true)

and then see in what order it adds the users to the database

I tried this and it works, thank you

u := User{Name: "Parent"}
db.Save(&u)
u2 := User{Name: "Child", Parent: &u.ID}
db.Save(&u2)
1 Like

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