@Mohamed_Ben_Rhouma (Mohamed Ben Rhouma) posted a new topic, subject "Foreign key constraint fail in recursive table". It read:

   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)
    [code] 
        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)
          
        }
        
    [/code]
    
    Error message  
    
    
    Capture21612×106 5.29 KB
    
    Capture1025×198 28.9 KB

After which, @johandalabacka (Johan Dahl) added

    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
    [code] 
        db.LogMode(true)
        
    [/code]
    
    and then see in what order it adds the users to the database

To which @Mohamed_Ben_Rhouma (Mohamed Ben Rhouma) replied

    I tried this and it works, thank you
    [code] 
        u := User{Name: "Parent"}
        db.Save(&u)
        u2 := User{Name: "Child", Parent: &u.ID}
        db.Save(&u2)
    [/code]

After which, @system (system) added

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


{'source': 'discourse', 'url': 'https://forum.golangbridge.org/t/foreign-key-constraint-fail-in-recursive-table/12668', 'title': 'Foreign key constraint fail in recursive table', 'views': 732, 'has_accepted_answer': False, 'word_count': 225, 'like_count': 1, 'reply_count': 1, 'participant_count': 2, 'posts': 4, 'tags': '', 'author': '@Mohamed_Ben_Rhouma (Mohamed Ben Rhouma)', 'participants': '@Mohamed_Ben_Rhouma (Mohamed Ben Rhouma), @johandalabacka (Johan Dahl), @system (system)', 'image_url': ['https://forum.golangbridge.org/uploads/default/optimized/2X/6/65ad86d8bc8573eea495f222132fe68bd457c645_2_1024x67.png'], 'created_at': '2019-02-23T11:17:59.586Z', 'last_posted_at': '2019-05-26T08:22:49.925Z'}