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 (
  _ ""

type User struct {
  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

  // Create
  u := User{Name: "Parent", Child: &User{Name:"Child"}}  

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


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"}
u2 := User{Name: "Child", Parent: &u.ID}
1 Like

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