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
After the gorm Update yesterday eve. All (code in question) works like the docs. :)