我正在尝试定义与 gorm ORM 的一对多关系。我一遍又一遍地阅读了所有文档。找不到办法。
func GetUser1(c *gin.Context) {
var user models.User
var activities models.UserActivity
query := DB.Debug().Find(&user, 1).Model(&user).Related(&activities).Error
if query != nil {
panic(query)
}
c.JSON(200, &user)
}
我的模特是..
type User struct {
Id int64
Username string
Password string `json:"-"`
Email string `json:",omitempty"`
UserActivities []UserActivity
}
type UserActivity struct {
Id int64
UserId int64 `json:"-"`
ActorId int64
CreatedAt time.Time
}
调试结果是
[2015-11-21 22:21:54] [3.17ms] SELECT * FROM `users` WHERE (`id` = '1')
[2015-11-21 22:21:54] [1.39ms] SELECT * FROM `user_activities` WHERE (`user_id` = '1')
但我得到空结果
{
"Id": 1,
"Username": "test1",
"Email": "test1@friesen.com",
"UserActivities": null
}
所有的主键和索引都是正确的。我也试过 puttin gorm:"primary_key"
,sql:"index"
但UserActivities
到目前为止没有运气。但是,如果我替换UserActivities []UserActivity
为UserActivities UserActivity
then 我只得到一行似乎是正确的但为什么UserActivities []UserActivity
没有给出结果