ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
#### 实例添加数据 ~~~ func (a *ArticleController) PostAdd() { title := a.GetString("title") desc := a.GetString("desc") content := a.GetString("content") o := orm.NewOrm() author := a.GetSession("user_name") user := models.User{} o.QueryTable(new(models.User)).Filter("username", author).One(&user) post := models.Article{ Title: title, Desc: desc, Content: content, } _, err2 := o.Insert(&post) if err2 != nil { a.Data["json"] = map[string]interface{}{"code": 500, "msg": err2} a.ServeJSON() } a.Data["json"] = map[string]interface{}{"code": 200, "msg": "添加成功"} a.ServeJSON() } ~~~ #### 实例删除数据 ~~~ func (a *ArticleController) PostDel() { id, err := a.GetInt("id") if err != nil { a.Ctx.WriteString("id参数错误") return } o := orm.NewOrm() _, err2 := o.QueryTable(new(models.Article)).Filter("id", id).Delete() if err2 != nil { a.Data["json"] = map[string]interface{}{"code": 500, "msg": err2} a.ServeJSON() return } a.Data["json"] = map[string]interface{}{"code": 200, "msg": "删除成功"} a.ServeJSON() } ~~~ #### 实例修改数据 ~~~ func (a *ArticleController) PostEdit() { id, err := a.GetInt("old_id") if err != nil { a.Ctx.WriteString("id参数错误") return } cover := a.GetString("old_cover") title := a.GetString("title") desc := a.GetString("desc") content := a.GetString("content") f, h, err := a.GetFile("cover") if err != nil { cover = cover } else { defer f.Close() // 生成时间戳,防止重名 timeUnix := time.Now().Unix() // int64类型 time_str := strconv.FormatInt(timeUnix, 10) // 将int64转为字符串 convert:转换 path := "static/upload/" + time_str + h.Filename // 保存获取到的文件 err1 := a.SaveToFile("cover", path) if err1 != nil { cover = cover } cover = path } o := orm.NewOrm() _, err3 := o.QueryTable(new(models.Article)).Filter("id", id).Update(orm.Params{ "cover": cover, "title": title, "desc": desc, "content": content, }) if err3 != nil { a.Data["json"] = map[string]interface{}{"code": 500, "msg": err3} a.ServeJSON() } a.Data["json"] = map[string]interface{}{"code": 200, "msg": "更新成功"} a.ServeJSON() } ~~~ #### 实例查询数据列表 ~~~ func (a *ArticleController) Get() { o := orm.NewOrm() qs := o.QueryTable(new(models.Article)) list := []models.Article{} qs.RelatedSel().All(&list) a.Data["list"] = list a.TplName = "article/index.html" } ~~~ #### 实例查询单条数据 ~~~ func (a *ArticleController) GetInfo() { id, err := a.GetInt("id") if err != nil { a.Ctx.WriteString("id参数错误") } o := orm.NewOrm() qs := o.QueryTable(new(models.Article)) list := models.Article{} qs.Filter("id", id).One(&list) a.Data["list"] = list a.TplName = "article/edit.html" } ~~~