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:"-"`
}

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

阅读 10.3k
1 个回答
db.Model(&Product{}).AddForeignKey(参数)

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

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题