1

一直在使用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超出第一个结果?

任何信息都会非常感谢。

4

0 回答 0