我正在尝试在递归表中添加外键,并启用onDelete
onUpdate
CASCADE
模式,以在删除父级时删除所有子级(与更新相同)。
我正在使用gorm作为ORM和MySQL 5.6的go 1.11.4
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)
}
我更新了此代码,终于成功了
答案 0 :(得分:0)
尝试以下方法:
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"`
}
我在使用AddForeignKey()
时遇到了麻烦,但是像这样对其进行硬编码似乎可行。