Insert for model with m2m in beego orm

2019-08-01 04:52发布

问题:

I have two models:

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
}

And with this code i`am trying to create new game with one player:

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)
    }

}

But it just create two inserts for game and player without rel-connection through "game_players" table which created automatically with 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`

I can`t find any special rules for working with m2m-models in docs and ask for help to community. How should i insert new row in table?

回答1:

According to this, you have to make a m2m object, after creating object game, like this:

m2m := models.ORM.QueryM2M(&game, "Players")

And instead of game.Players = []*models.Player{&playerA}, you write:

num, err := m2m.Add(playerA)

So, your function must look like this:

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)
    }
}

I hope this helps.

P.S.: BTW, you were right, It wasn't necessary to specify the name of the m2m table.



标签: go orm m2m beego