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).
I am using go 1.11.4 with gorm as ORM and MySQL 5.6
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"}
db.Save(&u)
u2 := User{Name: "Child", Parent: &u.ID}
db.Save(&u2)
}
I updated this code and it works finally
Try this instead:
type User struct {
gorm.Model
Name string
Child *User `gorm:"Foreignkey:Parent"`
Parent uint `sql:"type:bigint REFERENCES users(id) ON UPDATE CASCADE ON DELETE CASCADE"`
}
I've had trouble using AddForeignKey()
but hardcoding it like that seems to work.