相关代码如下:
type MainFields struct {
Id int `orm:"auto"`
Created time.Time `orm:"auto_now_add;type(datetime)"`
Updated time.Time `orm:"auto_now;type(datetime)"`
}
type Game struct {
MainFields
Players []*Player `orm:"rel(m2m)"`
}
type Player struct {
MainFields
Games []*Game `orm:"reverse(many)"`
NickName string
}
func insertTestData() {
var playerA models.Player
playerA.NickName = "CoolDude"
id, err := models.ORM.Insert(&playerA)
if err != nil {
log.Printf(err.Error())
} else {
log.Printf("Player ID: %v", id)
}
var game models.Game
id, err = models.ORM.Insert(&game)
if err != nil {
log.Printf(err.Error())
} else {
log.Printf("Game ID: %v", id)
}
m2m := o.QueryM2M(&game, "Players")
num, err := m2m.Add(playerA)
if err == nil {
log.Printf("Added nums: %v", num)
}
}
代码出自:
https://stackoverflow.com/questions/39770411/insert-for-model-with-m2m-in-beego-orm
网友评论