sqlite - GORM:引用同一张表
问题描述
我正在尝试创建一个引用同一个表的模型。
像这样:
import "gorm.io/gorm"
type Model struct {
gorm.Model
Code string `bson:"code" json:"code" gorm:"uniqueIndex"`
Name string `bson:"name" json:"name"`
Parent *Model `bson:"parent" json:"parent" gorm:"foreignKey:Parent"`
}
但是当我尝试创建一个新模型时,我收到了这个错误:failed to set value 0 to field Parent
.
如何将字段引用到同一个表中的项目?
解决方案
我找到了答案,您需要将其设置Parent
为 uint,然后在创建/更新时设置 ID。
像这样:
type Model struct {
gorm.Model
Code string `bson:"code" json:"code" gorm:"uniqueIndex,primaryKey"`
Name string `bson:"name" json:"name"`
Parent *uint `bson:"parent" json:"parent" gorm:"foreignKey:Parent"`
}