dongwei2030 2016-06-17 18:39
浏览 20
已采纳

与政府负荷相关的数据

playing around with the golang gorm orm, I have the following problem of comprehension:

My model looks like:

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
}

I use this in my revel controller, like this:

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)
}

The db tables are there: books, tags and book_tags Create with code first, inserting works fine.

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)
}

Ah and the view code:

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

In the gorm docs it says:

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

Tags are always empty iteration over books works fine. To it (invalid association []) but works for books.

Where is the mistake and how to do it right?

Thanks for your time and help.

Cheers

  • 写回答

1条回答 默认 最新

  • dongxiane0395 2016-06-18 12:12
    关注

    After the gorm Update yesterday eve. All (code in question) works like the docs. :)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度