type TreeNode struct {
ID uint `gorm:"primaryKey"`
TreeID uint
Label string
ParentID *uint
Children []TreeNode `gorm:"foreignKey:ParentID"`
} 这样的结构体怎么存,直接保存会报错
Error 1452 (23000): Cannot add or update a child row: a foreign key constraint fails (lianxi.tree_nodes, CONSTRAINT fk_trees_children FOREIGN KEY (tree_id) REFERENCES trees (id))
以下是具体代码
package main
import ( "gorm.io/driver/mysql" "gorm.io/gorm" "log" )
type Visualization struct {
ID uint gorm:"primaryKey"
Name string
Note string
Time string
Tree Tree gorm:"foreignKey:VisualizationID"
}
type Tree struct {
ID uint gorm:"primaryKey"
VisualizationID uint
Children []TreeNode gorm:"foreignKey:TreeID"
}
type TreeNode struct {
ID uint gorm:"primaryKey"
TreeID uint
Label string
ParentID *uint
Children []TreeNode gorm:"foreignKey:ParentID"
}
func main() { dsn := "root:root@tcp(127.0.0.1:3306)/lianxi?charset=utf8mb4&parseTime=True&loc=Local" db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{ //Logger: logger.Default.LogMode(logger.Info), // 设置日志级别为信息级别 }) if err != nil { panic("failed to connect database") }
// Migrate the schema
err = db.AutoMigrate(&Visualization{}, &Tree{}, &TreeNode{})
if err != nil {
log.Fatal("Failed to migrate: ", err)
}
createVisualization(db)
}
func createVisualization(db *gorm.DB) { visualization := Visualization{ Name: "Visualization 1", Note: "Sample note", Time: "2023-01-01", Tree: Tree{ Children: []TreeNode{ { Label: "Node 1", Children: []TreeNode{ {Label: "Node 1-1"}, {Label: "Node 1-2"}, }, }, { Label: "Node 2", }, }, }, }
db.Create(&visualization)
}