本章节主要学习下beego 文章评论的添加、删除、展示以及文章分类的关联处理。
controllers文件夹下添加reply.go,源码:
package controllers import ( "github.com/astaxie/beego" "myapp/models" ) type ReplyController struct { beego.Controller } func (this *ReplyController) Add() { tid := this.Input().Get("tid") err := models.AddReply(tid, this.Input().Get("nickname"), this.Input().Get("content")) if err != nil { beego.Error(err) } this.Redirect("/topic/view/"+tid, 302) } func (this *ReplyController) Delete() { if !checkAccount(this.Ctx) { return } tid := this.Input().Get("tid") err := models.DeleteReply(this.Input().Get("rid")) if err != nil { beego.Error(err) } this.Redirect("/topic/view/"+tid, 302) }
models文件下models.go添加:
func AddReply(tid, nickname, content string) error { tidNum, err := strconv.ParseInt(tid, 10, 64) if err != nil { return err } reply := &Comment{ Tid: tidNum, Name: nickname, Content: content, Created: time.Now(), } o := orm.NewOrm() _, err = o.Insert(reply) return err } func GetAllReplies(tid string) (replies []*Comment, err error) { tidNum, err := strconv.ParseInt(tid, 10, 64) if err != nil { return nil, err } replies = make([]*Comment, 0) o := orm.NewOrm() qs := o.QueryTable("comment") _, err = qs.Filter("tid", tidNum).All(&replies) return replies, err } func DeleteReply(rid string) error { ridNum, err := strconv.ParseInt(rid, 10, 64) if err != nil { return err } o := orm.NewOrm() reply := &Comment{Id: ridNum} _, err = o.Delete(reply) return err }
其他修改:
模板修改(添加评论、删除评论、以及分类展示等处理)
routers/router.go修改,添加回复的路由处理
controller/home.go修改,添加分类的读取,以及分类和文章的关联处理。
github:https://github.com/yangsir/beego_study
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/98494.html