我有模型:
type Book struct {
gorm.Model
Title string `json:"title"`
Author string `json:"author"`
Description string `json:"description"`
Category string `json:"Category"`
Publisher string `json:"publisher"`
AuthorsCard []*AuthorsCard `gorm:"many2many:book_authorscard; "json:"authorscard"`
}
type AuthorsCard struct {
gorm.Model
Name string `json:"name"`
Age int `json:"age"`
YearOfBirth int `json:"year"`
Biography string `json:"biography"`
}
db.AutoMigrate后(及模型。
我有一个创建函数:
func TestCreate() {
var testbook = models.Book{
Title: "Test",
Author: "tst",
AuthorsCard: []*models.AuthorsCard{
{
Age: 23,
Name: "test",
YearOfBirth: 1999,
Biography: "23fdgsdddTEST",
},
},
Description: "something",
}
db.Preload("AuthorsCard").Find(&models.Book{})
db.Create(&testbook)
}
尽管AuthorsCard有一些数据在它,我收到这个作为响应:
{
"ID": 78,
"CreatedAt": "2022-06-23T13:10:58.01629+03:00",
"UpdatedAt": "2022-06-23T13:10:58.01629+03:00",
"DeletedAt": null,
"title": "Test",
"author": "tst",
"description": "something",
"Category": "",
"publisher": "",
"authorscard": null
}
可以看到"authorscard"是零。
如何保存"authorscard"到数据库?我使用Gorm + postgresql,也用邮差发送了一些请求,结果是一样的-作者卡是空的
当按正确顺序调用时,代码正在工作:
func TestCreate() {
db := getDB()
db.AutoMigrate(&Book{}, AuthorsCard{})
var testbook = Book{
Title: "Test",
Author: "tst",
AuthorsCard: []*AuthorsCard{
{
Age: 23,
Name: "test",
YearOfBirth: 1999,
Biography: "23fdgsdddTEST",
},
},
Description: "something",
}
// 1. Create your testbook.
db.Create(&testbook)
// 2. Store it into a variable:
var b1 *Book
db.Preload("AuthorsCard").Find(&b1)
fmt.Println(b1.AuthorsCard[0].Age)
fmt.Println(b1.AuthorsCard[0].Name)
fmt.Println(b1.AuthorsCard[0].YearOfBirth)
fmt.Println(b1.AuthorsCard[0].Biography)
}
打印:
23测试199923 fdgsdddtest
你的JSON导出也可能失败,因为你传递了一个指向AuthorCard的指针,在这些情况下,编组并不总是正常工作。然而,GORM在这里做得很好。
静态检查也给了我一些提示:
type Book struct {
gorm.Model
Title string `json:"title"`
Author string `json:"author"`
Description string `json:"description"`
Category string `json:"Category"`
Publisher string `json:"publisher"`
AuthorsCard []*AuthorsCard `gorm:"many2many:book_authorscard" json:"authorscard"` // wrong space
}