我有两个模型:
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 game.Players = []*models.Player{&playerA} id, err = models.ORM.Insert(&game) if err != nil { log.Printf(err.Error()) } else { log.Printf("Game ID: %v", id) } }
但是,它只是为游戏和玩家创建了两个插入内容,而无需通过“”自动创建的“ game_players”表进行相关连接orm.RunSyncdb()。
orm.RunSyncdb()
2016/09/29 22:19:59 Player ID: 1 [ORM]2016/09/29 22:19:59 -[Queries/default] - [ OK / db.QueryRow / 11.0ms] - [INSERT INTO "player" ("created", "updated", "nick_name") VALUES ($1, $2, $3) RETURNING "id"] - `2016-09-29 22:19:59.8615846 +1000 VLAT`, `2016-09-29 22:19:59.8615846 +1000 VLAT`, `CoolDude` 2016/09/29 22:19:59 Game ID: 1 [ORM]2016/09/29 22:19:59 -[Queries/default] - [ OK / db.QueryRow / 11.0ms] - [INSERT INTO "game" ("created", "updated") VALUES ($1, $2) RETURNING "id"] - `2016-09-29 22:19:59.8725853 +1000 VLAT`, `2016-09-29 22:19:59.8725853 +1000 VLAT`
我在文档中找不到用于处理m2m模型的任何特殊规则,并寻求社区的帮助。我应该如何在表格中插入新行?
根据这个,你必须做出一个M2M对象,创建对象的游戏,像这样经过:
m2m := models.ORM.QueryM2M(&game, "Players")
而不是game.Players = []*models.Player{&playerA},您写道:
game.Players = []*models.Player{&playerA}
num, err := m2m.Add(playerA)
因此,您的函数必须如下所示:
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) } }
我希望这有帮助。
PS:顺便说一句,您是对的,没有必要指定m2m表的名称。