H5W3
当前位置:H5W3 > go > 正文

【go】gorm设置外键约束

两张表,一张是category,一张product,定义如下:

type Product struct {
ProductId  uint32 `gorm:"primary_key;type:int(11) unsigned auto_increment;"`
Category Category `gorm:"ForeignKey:CateIDRef;"`  //这里设置外键关联到category上去
CateIDRef uint16 `gorm:"type:mediumint(11) unsigned not null;"`
//CateTitle string `gorm:"type:varchar(30);not null;"`
//Title string `gorm:"type:varchar(30)  not null;"`
Summary string `gorm:"type:varchar(255)  not null;"`
Num  uint32  `gorm:"type:int unsigned  not null; default:0;"`
Price float64 `gorm:"type:decimal(10,2) unsigned not null;"`
Pics string        `gorm:"type:varchar(500); default: '';"`
CreateTime time.Time `gorm:"type:timestamp not null;default:current_timestamp;"`
ModifyTime time.Time `gorm:"type:timestamp on update current_timestamp;omitempty;default:current_timestamp;"`
}
type Category struct {
CateID uint16  `gorm:"primary_key;type:mediumint(11) not null unsigned auto_increment;"`
ParentID uint16  `gorm:"type:mediumint(11) unsigned;not null;"`
Title string `gorm:"type:varchar(30);not null;unique"`
CreateTime time.Time `gorm:"type:timestamp;not null;default:current_timestamp;"`
ModifyTime time.Time `gorm:"type:timestamp;not null on update current_timestamp;default:current_timestamp;"`
Level uint16 `gorm:"-"`
}

但是外键创建不成功,不知道具体原因在哪儿,求解答。

db.Model(&Product{}).AddForeignKey(参数)

另外这两张表不用设置主外键关联吧

回答

本文地址:H5W3 » 【go】gorm设置外键约束

评论 0

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址