gorm标签设置

作者: 五岁小孩 | 来源:发表于2021-02-23 08:49 被阅读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'==

    相关文章

      网友评论

        本文标题:gorm标签设置

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