Gorm只是在切片中预加载第一个结果

时间:2015-12-16 04:10:30

标签: go go-gorm

一直在使用gorm并且它太棒了,唯一的问题是嵌套preloading它似乎只填充第一个结果,这是我的代码:

// Shoutbox msg is the db struct
type ShoutboxMsg struct {
    gorm.Model
    UserID  int `sql:"index"`
    User    User
    Message string
}

// User is the User table in the database
type User struct {
    gorm.Model
    Username     string `sql:"not null;unique"`
    Email        string `sql:"not null;unique"`
    PasswordHash string `sql:"not null;unique"`
    UserLevel    int    `sql:"not null;default:0"`
    Characters   []Characters
    MainPosts    []ForumMainThreadsPosts
    ReplyPosts   []ForumMainPostsReplies
}

// Characters is a table in the database
type Characters struct {
    gorm.Model
    UserID             int    `sql:"index"`
    CharacterName      string `sql:"not null;unique"`
    CharacterServer    string `sql:"not null"`
    CharacterLevel     int    `sql:"not null"`
    CharacterMain      bool   `sql:"not null"`
    CharacterClass     string `sql:"not null"`
    CharacterPic       string `sql:"not null"`
    CharacterSpec      string `sql:"not null"`
    CharacterCSSClass  string `sql:"not null"`
    CharacterTalentImg string `sql:"not null"`
}

然后我加载它:

msgs := []ShoutboxMsg{}
db.Preload("User").Preload("User.Characters").Find(&msgs)

但它只填充了第一个:

msgs[0].User.Characters

-

msgs[1].User.Characters所有人都没有角色,但如果我这样做:

for i, msg := range msgs {
    characters := []Characters{}
    db.Model(msg.User).Related(&characters)
    *(&msgs[i].User.Characters) = characters
}

这似乎工作正常,但Preload不会超出第一个结果吗?

任何信息都会非常感谢。

0 个答案:

没有答案