Gorm加载相关数据

时间:2016-06-17 18:39:29

标签: go orm revel go-gorm

玩golang gorm orm,我有以下理解问题:

我的模型看起来像:

package models

import (
    "github.com/jinzhu/gorm"
    _ "github.com/jinzhu/gorm/dialects/sqlite"
)

type Book struct {
    gorm.Model
    Title       string `gorm:"size:255;not null;"`
    Desctiption string
    Tags        []Tag `gorm:"many2many:book_tags;"`
}

type Tag struct {
    ID   int
    Name string
}

我在我的狂欢控制器中使用它,如下所示:

import (
    "github.com/foobar/myrevel/app/models"
    "github.com/revel/revel"
)

type Book struct {
    GormController
}

func (c Book) Books() revel.Result {
    books := &[]models.Book{}
    // don't loads tags
    //Gdb.Order("id desc").Find(&books)
    // don't loads tags
    Gdb.Preload("Tags").Order("id desc").Find(&books).Related("Tags")

    return c.Render(books)
}

db表位于:books,tags和book_tags 首先使用代码创建,插入工作正常。

func (c Book) InsertTestData() revel.Result {
    book := &models.Book{
        Title:       "Hello Go lang",
        Desctiption: "The bueaty of golang",
        Tags:        []models.Tag{{Name: "Golang"}, {Name: "Go"}},
    }

    Gdb.NewRecord(&book)
    Gdb.Create(&book)
}

啊和视图代码:

<tbody>
  {{range .books}}
    <tr>
      <td>{{.Title}}</td>
      <td>
        {{.Desctiption}}<br />
        {{range .Tags}}
          {{.Name}}
        {{end}}
      </td>
    </tr>
  {{end}}
</tbody>

在gorm docs中它说:

db.Model(&user).Related(&emails)
//// SELECT * FROM emails WHERE user_id = 111; // 111 is user's primary key

http://jinzhu.me/gorm/associations.html#many-to-many

标签总是空的迭代书籍工作正常。对它(无效的关联[])但适用于书籍。

错误在哪里,怎么做?

感谢您的时间和帮助。

干杯

1 个答案:

答案 0 :(得分:0)

昨天前夕更新了gorm。所有(有问题的代码)都像文档​​一样工作。 :)