空无以求全
宁静以致远
当前位置:首页 > .html

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

作者:大熊空间发布时间:2022-02-19 17:09分类: 浏览:274评论:0


导读:Go踩过的坑之gorm外键关联字段无法插入 先知 在外键字段 的gorm标签中添加缺省==default:'galeone'==,则插入语句中当该字段为空时则不赋值 业务重现 ...

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'==


发表评论: