1 回答

TA貢獻1839條經驗 獲得超15個贊
當以正確的順序調用代碼時,代碼可以正常工作:
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 測試 1999 23fdgsdddTEST
此外,您的 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
}
- 1 回答
- 0 關注
- 133 瀏覽
添加回答
舉報