在 设置外键的时候不是只将字段和要关联的外键的结构体对应上就可以了, 还需要写一个关联的字段id 如:
type Blog struct {
ID uint `gorm:"primary_key"`
Title string `gorm:"not null;size:256"`
Content string `gorm:"type:text;not null"`
ShowContent string `gorm:"not null"`
LookNum int `gorm:"default:1"`
BlogType BlogType
BlogTypeID int // 还需要写上这
}
type BlogType struct {
ID uint `gorm:"primary_key"`
Name string
}
也可以指定
type Blog struct {
ID uint `gorm:"primary_key"`
Title string `gorm:"not null;size:256"`
Content string `gorm:"type:text;not null"`
ShowContent string `gorm:"not null"`
LookNum int `gorm:"default:1"`
BlogType BlogType `gorm:"ForeignKey:BlogTypeID"` // 指明用BlogTypeID 当做外键和 BlogType进行关联
BlogTypeID int // 还需要写上这
}
type BlogType struct {
ID uint `gorm:"primary_key"`
Name string
}
也可以指定外键关联的字段
type Blog struct {
ID uint `gorm:"primary_key"`
Title string `gorm:"not null;size:256"`
Content string `gorm:"type:text;not null"`
ShowContent string `gorm:"not null"`
LookNum int `gorm:"default:1"`
BlogType BlogType `gorm:"ForeignKey:BlogTypeID;AssociationForeignKey:ID"`
//这个AssiciationForignKey 可以指明BlogType中的哪个字段当做 关联的字段, 可以将ID改成Name
// 这样关联的字段就是Name了
BlogTypeID int // 还需要写上这
}
type BlogType struct {
ID uint `gorm:"primary_key"`
Name string
}