0
與golang格姆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>
在格姆文檔,它說:
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
標籤總是在書空迭代工作正常。它(無效的協會[]),但適用於書籍。
錯誤在哪裏,怎麼做對不對?
感謝您的時間和幫助。
乾杯