Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

自引用的结构体怎么存 #7009

Open
atheima opened this issue May 8, 2024 · 0 comments
Open

自引用的结构体怎么存 #7009

atheima opened this issue May 8, 2024 · 0 comments
Assignees
Labels
type:question general questions

Comments

@atheima
Copy link

atheima commented May 8, 2024

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)

}

The document you expected this should be explained

Expected answer

@atheima atheima added the type:question general questions label May 8, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
type:question general questions
Projects
None yet
Development

No branches or pull requests

2 participants