我是一个新手,我决定创建一个RestAPI来练习技能。现在我要在User之间建立一对多的关系书和实体。但是当我试图保存Book时实体到数据库,它显示我这样的错误:
invalid field found for struct test/entity.UserEntity's field Books: define a valid foreign key for relations or implement the Valuer
/Scanner interface
下面是我的代码:
UserEntity
type UserEntity struct {
gorm.Model
Username string `gorm:"unique;not null"`
Email string `gorm:"unique;not null"`
Password string `gorm:"not null"`
Books []BookEntity `gorm:"constraint:OnUpdate:CASCADE,OnDelete:SET NULL;"`
}
func (*UserEntity) TableName() string {
return "users"
}
BookEntity
type BookEntity struct {
gorm.Model
Name string `gorm:"not null"`
Isbn int `gorm:"unique;not null"`
AuthorID uint
}
func (*BookEntity) TableName() string {
return "books"
}
BookAddModel
type BookAddModel struct {
Name string `json:"name"`
Isbn int `json:"isbn"`
}
func (bookModel *BookAddModel) ToModel(ctx *gin.Context) {
ctx.Bind(&bookModel)
}
下面是我向数据库中添加实体的代码
func AddBook(bookModel models.BookAddModel, author *entity.UserEntity) entity.BookEntity {
var book entity.BookEntity
mapstructure.Decode(bookModel, &book)
config.DbSession.Create(&book) // <<<< here's error
author.Books = append(author.Books, book)
config.DbSession.Save(author)
return book
}
配置
var DbSession *gorm.DB
var PostgresData = "host=localhost user=postgres password=4122 dbname=gorm port=5432 sslmode=disable TimeZone=Asia/Shanghai"
那么问题是什么呢?如果你知道,请告诉我。我真的很感激!
您应该为UserEntity.Books
设置foreignKey
:
type UserEntity struct {
...
Books []BookEntity `gorm:"foreignKey:AuthorID,..."`
}
不要忘记先删除表,然后重新运行AutoMigration
s:
db.AutoMigrate(&UserEntity{})
db.AutoMigrate(&BookEntity{})