gorm标签设置
2021-02-23 本文已影响0人
五岁小孩
gorm标签设置
-
设置缺省值(default:'galeone')
当model字段中存在外键时,插入数据时又为空时,报错:
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;default:'galeone'"` } 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{ StuId: 1111, 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)
插入语句:
INSERT INTO
stu
(StuId
,Name
,SchId
) VALUES (1111,'xj',0)由于SchId为外键,0值插入报错不存在
正确的sql:
INSERT INTO
stu
(StuId
,Name
) VALUES (1111,'xj')在字段标签gorm中添加==default:'galeone'==