下面是一个程序(基于 GORM),它定义了两个数据库表(users和cards),其逻辑是用户拥有一张卡。然后它创建数据库,填写它,搜索并打印出其中唯一的记录。我的问题:最终搜索中的卡是空的,它没有附加到用户。从数据库的角度来看,一切都很好:SELECT * FROM usersid name card_id1 john 1SELECT * FROM cardsid number1 42请注意,card_id在第一个结果中正确指向id卡的。为什么我的最后一次搜索返回的是一张空卡片?package mainimport ( "fmt" "gorm.io/driver/sqlite" "gorm.io/gorm")type User struct { ID uint Name string UserCard Card CardID uint}type Card struct { ID uint Number string}func main() { // initialize the database db, _ := gorm.Open(sqlite.Open("mytest.sqlite"), &gorm.Config{}) db.AutoMigrate(&User{}, &Card{}) // create one card db.Create(&Card{ Number: "42", }) // find that card var myCard Card db.Where(map[string]interface{}{"number": "42"}).First(&myCard) // create a user with that card db.Create(&User{ Name: "john", UserCard: myCard, }) // find that user var myUser User db.Where(map[string]interface{}{"name": "john"}).First(&myUser) // print his name and card number // the problem is here: the card number is empty, as if the card was not linked fmt.Printf("name: %v, number: %v", myUser.Name, myUser.UserCard.Number)}// output// name: john, number:
- 1 回答
- 0 关注
- 114 浏览
添加回答
举报
0/150
提交
取消