美文网首页Golang 入门资料+笔记
Go踩过的坑之gorm外键关联字段null值无法插入

Go踩过的坑之gorm外键关联字段null值无法插入

作者: 五岁小孩 | 来源:发表于2021-03-14 11:14 被阅读0次

Go踩过的坑之gorm外键关联字段无法插入

先知

在外键字段 的gorm标签中添加缺省==default:'galeone'==,则插入语句中当该字段为空时则不赋值

业务重现

type School struct{
    SchId    int     `json:"SchId"      gorm:"column:SchId;type:int;size:11;not null;primary_key;AUTO_INCREMENT;"`
    Name      string  `json:"Name"        gorm:"column:Name;type:varchar;size:500;not null;"`
}
type Stu struct{
    StuId    int     `json:"SchId"      gorm:"column:SchId;type:int;size:11;not null;primary_key;AUTO_INCREMENT;"`
    Name      string  `json:"Name"        gorm:"column:Name;type:varchar;size:500;not null;"`
    SchId    int     `json:"SchId"      gorm:"column:SchId;type:int;size:11;"`
}
func main() {
    addModel := model.Stu{
        Name:   "xj",
    }
    err:=dao.insert(&addModel)
    if err.Error!=nil{
        fmt.Println(err)
    }
}

Error 1452: Cannot add or update a child row: a foreign key constraint fails
(ew_nfdas.stu, CONSTRAINT fk_stud_schid FOREIGN KEY (SchId) REFERENCES school (SchId) ON DELETE SET NULL ON UPDATE SET NULL)

大概意思是:在插入stu表时SchId字段的值在关联表School中无法找到

插入语句:

INSERT INTO stu (StuId,Name,SchId) VALUES (1111,'xj',0)

由于SchId为外键,0值插入报错不存在

正确的sql:

INSERT INTO stu (StuId,Name) VALUES (1111,'xj')

在字段标签gorm中添加==default:'galeone'==

相关文章

网友评论

    本文标题:Go踩过的坑之gorm外键关联字段null值无法插入

    本文链接:https://www.haomeiwen.com/subject/pgugxltx.html