玩弄 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)
}
数据库表在那里:书籍、标签和 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 文档中它说:
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
书籍上的标签总是空迭代工作正常。对它(无效的关联 [])但适用于书籍。
错误在哪里以及如何正确处理?
感谢您的时间和帮助。
干杯