美文网首页
beego的orm进行多对多的数据插入

beego的orm进行多对多的数据插入

作者: 王炎杰 | 来源:发表于2018-04-27 09:21 被阅读0次

    相关代码如下:

    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

    相关文章

      网友评论

          本文标题:beego的orm进行多对多的数据插入

          本文链接:https://www.haomeiwen.com/subject/eazvlftx.html