beego ORM的应用 - Go语言中文社区

beego ORM的应用


controllers目录下新建文件db.go

type SaveController struct {
    beego.Controller
}

func (this *SaveController) CreateData()  {
    // 接受参数 id title views topic_count topic_last_user_id 
    // 这里参数没有任何含义 试验用而已
    Id := this.Input().Get("id")
    Title := this.Input().Get("title")
    Views := this.Input().Get("views")
    TopicCount := this.Input().Get("topic_count")
    TopicLastUserId := this.Input().Get("topic_last_user_id")

    // 参数转为int类型
    int_id, _ := strconv.Atoi(Id)
    int_views, _ := strconv.Atoi(Views)
    int_topic_count, _ := strconv.Atoi(TopicCount)
    intid_topic_last_user_id, _ := strconv.Atoi(TopicLastUserId)

    // 时间
    Created := time.Now()
    TopicTime := time.Now()

    // 使用 ORM 前要先注册数据库
    // models.RegisterDB() 要在main函数中注册,注册一次 
    o := orm.NewOrm()
    store := models.Store{int_id, Title, Created, int_views, TopicTime, int_topic_count, intid_topic_last_user_id}

    // 数据库插入数据
    _, err := o.Insert(&store)
    // 返回 json 数据
    if err != nil {
        //this.Ctx.Output.SetStatus(400)
        //this.Ctx.Output.Body([]byte())
        this.Data["json"] = map[string]interface{}{"code": 201, "msg": string(err.Error())}
        this.ServeJSON()
        return
    }
    this.Data["json"] = map[string]interface{}{"code": 200, "msg": "success"}
    this.ServeJSON()
}
版权声明:本文来源简书,感谢博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://www.jianshu.com/p/784f7f179c14
站方申明:本站部分内容来自社区用户分享,若涉及侵权,请联系站方删除。
  • 发表于 2020-01-12 11:59:02
  • 阅读 ( 788 )
  • 分类:Go

0 条评论

请先 登录 后评论

官方社群

GO教程

猜你喜欢