Golang NewOrm示例

说明

golang neworm示例是从最受好评的开源项目中提取的实现代码,你可以参考下面示例的使用方式。

编程语言: Golang

命名空间/包名称: github.com/astaxie/beego/orm

示例#1
文件: model.go 项目: sllt/ac

func AddTopic(uid, name, content, pic, nid, fid string) error {
	nidNum, err := strconv.ParseInt(nid, 10, 64)
	if err != nil {
		return err
	}
	fidNum, _ := strconv.ParseInt(fid, 10, 64)
	o := orm.NewOrm()
	topic := &Topic{
		Uid:     uid,
		Nid:     nidNum,
		Fid:     fidNum,
		Name:    name,
		Content: content,
		Pic:     pic,
		Created: time.Now(),
		Updated: time.Now(),
	}
	//判断是否是子串,如果是就更新父串的Update时间
	if fidNum != 0 {
		beego.Info("qwe:")
		otmp := orm.NewOrm()
		qst := otmp.QueryTable("topic")
		tf := new(Topic)
		err = qst.Filter("id", fidNum).One(tf)
		tf.Updated = time.Now()
		otmp.Update(tf)

	}
	_, err = o.Insert(topic)
	return err
}

示例#2
文件: problem.go 项目: jango2015/ojsite

// put problem into trash
func (this *Problem) TrashProblem(id int) error {
	o := orm.NewOrm()
	ob := orm.NewOrm()
	var pro Problem
	var prob ProblemBank
	var err error
	var num int64

	if id > 0 {
		// read from problem
		pro.Id = id
		err = o.Read(&pro, "Id")
		if err != nil {
			return err
		}

		// read from problem bank
		prob.Id = pro.Pbid
		err = ob.Read(&prob, "Id")
		if err == nil {
			prob.Status = "deleted"
			ob.Update(&prob)
		}

		num, err = o.Delete(&pro)
	} else {
		return errors.New("at least one valid param")
	}

	if num == 0 {
		return errors.New("no row to delete")
	}

	return err
}

示例#3
文件: live_video.go 项目: qiniudemo/qiniu-live-server

//@param streamId
//@param streamTitle
//@return publishId if err==nil and pubilshId==nil, not allow taken
//streamId can only be taken once a time
func CreateNewPublish(userId int, streamId, streamTitle string, streamQuality, streamOrientation int) (publishId string, err error) {
	timestamp := time.Now().Unix()
	orm.NewOrm().QueryTable("LiveVideo").Filter("StreamId", streamId).Filter("EndTime", 0).Update(orm.Params{
		"EndTime": timestamp,
	})

	publishId = utils.Md5Hash(fmt.Sprintf("%s:%s:%d", streamId, streamTitle, timestamp))
	user := User{Id: userId}
	newPublish := LiveVideo{
		User:        &user,
		PublishId:   publishId,
		Title:       streamTitle,
		StreamId:    streamId,
		Quality:     streamQuality,
		Orientation: streamOrientation,
		StartTime:   timestamp,
	}

	_, cErr := orm.NewOrm().Insert(&newPublish)
	if cErr != nil {
		err = cErr
		return
	}

	return
}

示例#4
文件: team.go 项目: Liuyanglong/uic

func PutAdminInTeam(tid int64, uids string) error {
	if uids == "" {
		return nil
	}

	uidArr := strings.Split(uids, ",")
	for i := 0; i < len(uidArr); i++ {
		uid := uidArr[i]
		if uid == "" {
			continue
		}

		id, err := strconv.Atoi(uid)
		if err != nil {
			return err
		}

		_, err = orm.NewOrm().Raw("insert into rel_team_user(tid,uid,is_admin) values(?, ?, 1)", tid, id).Exec()
		if err != nil {
			_, err = orm.NewOrm().Raw("update rel_team_user set is_admin = 1 where tid=? and uid=?", tid, id).Exec()
			if err != nil {
				return err
			}
		}
	}

	return nil
}

示例#5
文件: MiniUiOrm.go 项目: dongjun111111/notes

func SaveMiniUIData(ModelName string, data string, diy interface{}) (err error) {
	//TODO:加入修改删除时的身份判断。只能修改删除自己创建的。加filter
	beego.Debug("SaveMiniUIData(ModelName = [%#v], data = [%#v], diy = [%#v])\n", ModelName, data, diy)

	//根据名称获取Model
	reflecty, _ := ModelCache.Get(ModelName)
	//得到实例
	reflectx := reflecty()

	//整理为可识别格式
	var dataList DataList
	json.Unmarshal([]byte(data), &dataList)

	//按struct 遍历得到定义,及得到的值
	for _, SingleItem := range dataList.List {
		state := SingleItem["_state"]
		beego.Debug("state是", state)
		if state == nil || state == "" {
			state = "modified"
			beego.Debug("state改为默认的", state)
		}
		if state != "" {

			Params := make(orm.Params)

			//格式化miniui过来的时间,得到修改过的字段放到m中
			err = MiniUIDataUpdate(reflectx, SingleItem, Params, state.(string), diy)
			if err != nil {
				beego.Error("MiniUIDataUpdate", err)
			}
			//beego.Debug("更新参数",Params)
			switch state {
			case "modified":
				pk := GetModelPk(reflectx)
				//获取表名,要求必须有TableName方法
				if tablenameMC := reflect.ValueOf(reflectx).MethodByName("TableName"); tablenameMC.IsValid() {
					tablename := tablenameMC.Call(nil)[0].Interface().(string)
					//fmt.Println("dddd",tablename.Interface().(string))
					//orm.NewOrm().QueryTable(reflect.TypeOf(reflectx).Elem().Name()).Filter(pk, SingleItem[pk]).Update(Params)
					beego.Debug("更新参数", Params)
					count, err := orm.NewOrm().QueryTable(tablename).Filter(pk, SingleItem[pk]).Update(Params)
					beego.Debug("更新参数", count, err, Params)

				} else {
					beego.Error("获取表名,要求必须有TableName方法")
					return errors.New(fmt.Sprintf("获取表名,要求必须有TableName方法"))

				}

			case "added":
				_, err = orm.NewOrm().Insert(reflectx)
			case "removed":

				_, err = orm.NewOrm().Delete(reflectx)

			}
		}
	}
	return err
}

示例#6
文件: session.go 项目: qiniudemo/qiniu-live-server

func SetSession(userId int, sessionId string) (err error) {
	var session Session
	qs := orm.NewOrm().QueryTable("Session").Filter("UserId", userId)
	qErr := qs.Limit(1).One(&session)
	if qErr != nil {
		if qErr != orm.ErrNoRows {
			err = errors.New(fmt.Sprintf("set session error, %s", qErr.Error()))
			return
		}
	}
	if session.Id != 0 {
		session.SessionId = sessionId
		_, uErr := orm.NewOrm().Update(&session, "SessionId")
		if uErr != nil {
			err = errors.New(fmt.Sprintf("update session error, %s", uErr.Error()))
			return
		}
	} else {
		session.UserId = userId
		session.SessionId = sessionId
		_, cErr := orm.NewOrm().Insert(&session)
		if cErr != nil {
			err = errors.New(fmt.Sprintf("create session error, %s", cErr.Error()))
			return
		}
	}
	return
}

示例#7
文件: auth.go 项目: EPICPaaS/wetalk

func (m *User) Insert() error {

	id := m.Id

	//fmt.Println("id...")
	//fmt.Println(m.Id)

	//orm.Debug = true
	m.Rands = GetUserSalt()

	if _, err := orm.NewOrm().Insert(m); err != nil {

		return err
	}

	fmt.Println(m.Email)
	fmt.Println(m.Id)

	o := orm.NewOrm()
	o.QueryTable("user").Filter("email", m.Email).Update(orm.Params{
		"id": id,
	})

	//fmt.Printf("Affected Num: %s, %s", num, err)

	return nil
}

示例#8
文件: ops_monitor.go 项目: alex8023/citycloud.cf-deploy-ui

//同一个agent的结果保存20条记录,滚动覆盖记录
func (monitor *Monitor) SaveOrUpdate() error {
	count, err := orm.NewOrm().QueryTable(new(Monitor)).Filter("AgentId", monitor.AgentId).Count()

	if err != nil {
		beego.Error("Count Monitor error : %s", err)
		return err
	}

	if count < utils.Monitor_Agent_Size {
		return monitor.Save()
	}

	var _monitor Monitor
	//选取同一个agent_id 的最早update的记录
	err = orm.NewOrm().QueryTable(new(Monitor)).Filter("AgentId", monitor.AgentId).OrderBy("Updated").Limit(1).One(&_monitor)

	if err == orm.ErrNoRows {
		return monitor.Save()
	}

	if err == nil {
		monitor.Id = _monitor.Id
		return monitor.Update()
	}

	return err
}

示例#9
文件: cloudfoundry.go 项目: alex8023/citycloud.cf-deploy-ui

func (resourcesPools *ResourcesPools) Load() error {

	errors := orm.NewOrm().Read(resourcesPools, "Id")
	if errors != nil {
		beego.Error("Read ResourcesPools error : %s", errors)
		_, err := orm.NewOrm().Insert(resourcesPools)
		if err != nil {
			beego.Error("Insert ResourcesPools error %s ", err)
		}
	}
	return errors
}

示例#10
文件: cloudfoundry.go 项目: alex8023/citycloud.cf-deploy-ui

func (netWorks *NetWorks) Load() error {

	errors := orm.NewOrm().Read(netWorks, "NetWorkName")
	if errors != nil {
		beego.Error("Read NetWorks error : %s", errors)
		_, err := orm.NewOrm().Insert(netWorks)
		if err != nil {
			beego.Error("Insert NetWorks error %s ", err)
		}
	}
	return errors
}

示例#11
文件: base.go 项目: wuwenbao/GoWebSSH

func CreateTable() {
	name := "default"                          //数据库别名
	force := false                             //不强制建数据库
	verbose := true                            //打印建表过程
	err := orm.RunSyncdb(name, force, verbose) //建表
	if err != nil {
		beego.Error(err)
	}
	exit := orm.NewOrm().QueryTable("user").Filter("username", "admin").Exist()
	if !exit {
		user := User{Username: "admin", Password: "admin"}
		orm.NewOrm().Insert(&user)
	}
}

示例#12
文件: post.go 项目: ShinichR/myBlog

func (m *Post) Delete() error {
	if m.Tags != "" {
		o := orm.NewOrm()
		oldtags := strings.Split(strings.Trim(m.Tags, ","), ",")
		//标签统计-1
		o.QueryTable(&Tag{}).Filter("name__in", oldtags).Update(orm.Params{"count": orm.ColValue(orm.Col_Minus, 1)})
		//删掉tag_post表的记录
		o.QueryTable(&TagPost{}).Filter("postid", m.Id).Delete()
	}
	if _, err := orm.NewOrm().Delete(m); err != nil {
		return err
	}
	return nil
}

示例#13
文件: microbosh.go 项目: alex8023/citycloud.cf-deploy-ui

func (netWork *NetWork) Load() error {
	queryOneErr := orm.NewOrm().QueryTable(netWork).One(netWork, "Id")
	if queryOneErr != nil {
		beego.Error("Query One failed %s", queryOneErr)
	}
	errors := orm.NewOrm().Read(netWork, "Id")
	if errors != nil {
		beego.Error("Read NetWork error : %s", errors)
		_, err := orm.NewOrm().Insert(netWork)
		if err != nil {
			beego.Error("Insert NetWork error %s ", err)
		}
	}
	return errors
}

示例#14
文件: cloudfoundry.go 项目: alex8023/citycloud.cf-deploy-ui

func (cloudFoundryJobs *CloudFoundryJobs) Load() error {
	errors := orm.NewOrm().Read(cloudFoundryJobs, "JobName")
	if errors == nil {
		cloudFoundryJobs.StaticIp = strings.Split(cloudFoundryJobs.StaticIps, ",")
	}
	if errors != nil {
		beego.Error("Read CloudFoundryJobs error : %s", errors)
		cloudFoundryJobs.StaticIps = strings.Join(cloudFoundryJobs.StaticIp, ",")
		_, err := orm.NewOrm().Insert(cloudFoundryJobs)
		if err != nil {
			beego.Error("Insert CloudFoundryJobs error %s ", err)
		}
	}
	return errors
}

示例#15
文件: microbosh.go 项目: alex8023/citycloud.cf-deploy-ui

func (resources *Resources) Load() error {
	queryOneErr := orm.NewOrm().QueryTable(resources).One(resources, "Id")
	if queryOneErr != nil {
		beego.Error("Query One failed %s", queryOneErr)
	}
	errors := orm.NewOrm().Read(resources, "Id")
	if errors != nil {
		beego.Error("Read Resources error : %s", errors)
		_, err := orm.NewOrm().Insert(resources)
		if err != nil {
			beego.Error("Insert Resources error %s ", err)
		}
	}
	return errors
}

示例#16
文件: problem_bank.go 项目: jango2015/ojsite

// 通过problem
// id bank中的ID
func (this *ProblemBank) AcceptProblem(id int) error {
	o := orm.NewOrm()
	var prob ProblemBank
	var err error

	prob.Id = id

	// read problem in problem bank
	err = o.Read(&prob, "Id")

	if err != nil {
		return err
	}

	// create problem
	var pro Problem
	op := orm.NewOrm()

	pro.Title = prob.Title
	pro.Pbid = prob.Id
	pro.Type = prob.Type
	pro.Description = prob.Description
	pro.PreCode = prob.PreCode
	pro.IoData = prob.IoData
	pro.Tags = prob.Tags
	pro.Level = "public"

	log.Blueln("[problem copy from bank to list]")
	log.Blueln(pro)

	// insert into problem
	pid, err := op.Insert(&pro)
	if err != nil {
		return err
	} else if pid == 0 {
		return errors.New("insert error, id is 0.")
	}

	// update problem bank
	prob.Status = "ok"
	_, err = o.Update(&prob)
	if err != nil {
		return err
	} else {
		return nil
	}

}

示例#17
文件: user.go 项目: Piasy/BeegoTDDBootStrap

// TODO return more detailed error number
// NOTE: this will do a fully update, so the user must be read from DB, and then update its field
func UpdateUser(user *User) int {
	o := orm.NewOrm()
	err := o.Begin()
	if err != nil {
		beego.Warning("UpdateUser fail: ", err)
		return utils.ERROR_CODE_SYSTEM_ERROR
	}

	var errNum int
	for i := 0; i < DB_UNIQUE_CONFLICT_TRY; i++ {
		user.UpdateAt = utils.GetTimeMillis()
		errNum = updateUserInternal(&o, user)
		if errNum == 0 {
			break
		}
		time.Sleep(1 * time.Millisecond)
	}
	if errNum > 0 {
		o.Rollback()
		return errNum
	} else {
		err = o.Commit()
		if err != nil {
			beego.Warning("UpdateUser fail: commit fail ", err)
			o.Rollback()
			return utils.ERROR_CODE_SYSTEM_ERROR
		}
	}

	return 0
}

示例#18
文件: user.go 项目: Piasy/BeegoTDDBootStrap

func VerifyUserByPhone(phone *string, secret string) (*User, int) {
	utils.AssertNotEmptyString(phone)
	o := orm.NewOrm()
	user := User{Phone: phone}
	err := o.Read(&user, "Phone")

	if err != nil {
		return nil, utils.ERROR_CODE_USERS_USER_NOT_EXISTS
	}

	if utils.Secret2Password("phone:"+*phone, secret) != user.Password {
		return nil, utils.ERROR_CODE_TOKENS_PASSWORD_MISMATCH
	}

	for i := 0; i < DB_UNIQUE_CONFLICT_TRY; i++ {
		user.Token = utils.GenToken()
		user.UpdateAt = utils.GetTimeMillis()
		_, err = o.Update(&user)
		if err == nil {
			return &user, 0
		}
		time.Sleep(1 * time.Millisecond)
	}

	beego.Warning("VerifyUser, update token fail: ", err)
	return nil, utils.ERROR_CODE_SYSTEM_ERROR
}

示例#19
文件: category.go 项目: cwen-coder/cwengo.com

func GetAllCategories() ([]*Category, error) {
	o := orm.NewOrm()
	cates := make([]*Category, 0)
	qs := o.QueryTable("category")
	_, err := qs.All(&cates)
	return cates, err
}

示例#20
文件: models.go 项目: 443752009/go-web-foundation

func DeleteReply(rid string) error {
	ridNum, err := strconv.ParseInt(rid, 10, 64)
	if err != nil {
		return err
	}

	o := orm.NewOrm()

	var tidNum int64
	reply := &Comment{Id: ridNum}
	if o.Read(reply) == nil {
		tidNum = reply.Tid
		_, err = o.Delete(reply)
		if err != nil {
			return err
		}
	}

	replies := make([]*Comment, 0)
	qs := o.QueryTable("comment")
	_, err = qs.Filter("tid", tidNum).OrderBy("-created").All(&replies)
	if err != nil {
		return err
	}

	topic := &Topic{Id: tidNum}
	if o.Read(topic) == nil {
		topic.ReplyTime = replies[0].Created
		topic.ReplyCount = int64(len(replies))
		_, err = o.Update(topic)
	}
	return err
}

示例#21
文件: models.go 项目: 443752009/go-web-foundation

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)
	if err != nil {
		return err
	}

	topic := &Topic{Id: tidNum}
	if o.Read(topic) == nil {
		topic.ReplyTime = time.Now()
		topic.ReplyCount++
		_, err = o.Update(topic)
	}
	return err
}

示例#22
文件: models.go 项目: 443752009/go-web-foundation

func DeleteTopic(tid string) error {
	tidNum, err := strconv.ParseInt(tid, 10, 64)
	if err != nil {
		return err
	}

	o := orm.NewOrm()

	var oldCate string
	topic := &Topic{Id: tidNum}
	if o.Read(topic) == nil {
		oldCate = topic.Category
		_, err = o.Delete(topic)
		if err != nil {
			return err
		}
	}

	if len(oldCate) > 0 {
		cate := new(Category)
		qs := o.QueryTable("category")
		err = qs.Filter("title", topic.Category).One(cate)
		if err == nil {
			cate.TopicCount--
			_, err = o.Update(cate)
		}
	}
	return err
}

示例#23
文件: file.go 项目: dw250100785/blog-1

// 文件列表
// page 页码
// numPerPage 每页条数
// 返回值:
// []orm.Params 文章
// bool 是否有下一页
// int 总页数
// error 错误
func GetFileList(page int, numPerPage int) ([]orm.Params, bool, int, error) {
	// numPerPage := 6
	sql1 := "select * from file order by time desc limit ?," + fmt.Sprintf("%d", numPerPage)
	sql2 := "select count(*) as number from file"
	var maps, maps2 []orm.Params
	o := orm.NewOrm()
	num, err := o.Raw(sql1, numPerPage*(page-1)).Values(&maps)
	o.Raw(sql2).Values(&maps2)

	number, _ := strconv.Atoi(maps2[0]["number"].(string))

	var addFlag int
	if 0 == (number % numPerPage) {
		addFlag = 0
	} else {
		addFlag = 1
	}

	pages := number/numPerPage + addFlag

	var flagNextPage bool
	if pages == page {
		flagNextPage = false
	} else {
		flagNextPage = true
	}

	if err == nil && num > 0 {
		return maps, flagNextPage, pages, nil
	} else {
		return nil, false, pages, err
	}
}

示例#24
文件: file.go 项目: dw250100785/blog-1

// 添加文件信息到数据库
// filename 文件名
// path 路径
// store 存储类型
// mime 文件类型信息
// error 返回错误
func AddFile(filename string, path string, store string, mime string) (int64, error) {
	o := orm.NewOrm()
	var file File
	file.Filename = filename
	file.Path = path
	if "local" == store {
		file.Store = "local"
	} else {
		file.Store = "oss"
	}
	file.Mime = mime

	// select count(*) from file where path=path
	sql := "select count(*) as number from file where path=?"
	var maps []orm.Params
	o.Raw(sql, path).Values(&maps)
	num, _ := strconv.Atoi(maps[0]["number"].(string))

	var err error
	var id int64
	if 0 == num {
		id, err = o.Insert(&file)
	} else {
		id, err = o.Update(&file, "path")
	}

	if err == nil {
		return id, nil
	} else {
		return id, err
	}
}

示例#25
文件: channel_test.go 项目: chenbk85/nephele

func TestGetChannels(t *testing.T) {
	InitDBForTest()
	m, e := channel.GetChannels()
	if e.Err != nil {
		t.Error(e.Err)
	}
	mcount := len(m)

	//insert
	o := orm.NewOrm()
	o.Raw("INSERT INTO channel(name,code) VALUES(?,?)", "test", "ZZ").Exec()
	m1, e := channel.GetChannels()
	m1count := len(m1)
	if mcount != m1count {
		t.Error("refresh error")
	}

	//refresh time  get
	getChannelsTime = time.Now().Add(-2 * time.Minute)
	m2, e := channel.GetChannels()
	m2count := len(m2)
	if m2count == mcount {
		t.Error("refresh fail")
	}

	//delete
	o.Raw("DELETE from channel WHERE name=?", "test").Exec()
}

示例#26
文件: comment.go 项目: Genffy/api.genffy.com

// @router /get/:postId [get]
func (c *CommentController) Get() {
	var comments []*models.Comment
	postId := c.Ctx.Input.Param(":postId")
	res := &common.CommentResponse{}

	defer func() {
		c.Data["json"] = res
		c.ServeJSON()
	}()

	if postId == "" {
		res.Code = 1
		res.Msg = "postId not empty"
		return
	}
	o := orm.NewOrm()
	num, err := o.QueryTable(new(models.Comment)).Filter("PostId__iexact", postId).All(&comments)
	if err == orm.ErrNoRows {
		fmt.Println("result is empty")
	} else if err == orm.ErrMissPK {
		fmt.Println("can't get key")
	} else {
		fmt.Println("the result is %v", num)
	}
	// TODO formate results
	res.Code = 1
	res.Msg = "success"
	res.Data = comments
	return
}

示例#27
文件: article.go 项目: royburns/blog

// 同关键词文章列表
// select * from article where keywords like '%keyword%'
// 返回值:
// []orm.Params 文章
// bool 是否有下一页
// error 错误
func ListByKeyword(keyword string, page int, numPerPage int) ([]orm.Params, bool, int, error) {
	// numPerPage := 6
	sql1 := "select * from article where keywords like ? order by time desc limit ?,?"
	sql2 := "select count(*) as number from article where keywords like ?"
	var maps, maps2 []orm.Params
	o := orm.NewOrm()
	num, err := o.Raw(sql1, fmt.Sprintf("%%%s%%", keyword), numPerPage*(page-1), numPerPage).Values(&maps)
	o.Raw(sql2, fmt.Sprintf("%%%s%%", keyword)).Values(&maps2)

	number, _ := strconv.Atoi(maps2[0]["number"].(string))

	var addFlag int
	if 0 == (number % numPerPage) {
		addFlag = 0
	} else {
		addFlag = 1
	}

	pages := number/numPerPage + addFlag

	var flagNextPage bool
	if pages == page {
		flagNextPage = false
	} else {
		flagNextPage = true
	}

	if err == nil && num > 0 {
		return maps, flagNextPage, pages, nil
	} else {
		return nil, false, pages, err
	}
}

示例#28
文件: user.go 项目: Piasy/BeegoTDDBootStrap

func UserPhoneExists(phone *string) bool {
	utils.AssertNotEmptyString(phone)
	o := orm.NewOrm()
	user := User{Phone: phone}
	err := o.Read(&user, "Phone")
	return err == nil
}

示例#29
文件: user.go 项目: Piasy/BeegoTDDBootStrap

func AuthWithWeiXin(openid, token string) (*User, int) {
	authUser, errNum := utils.AuthWithWeiXin(openid, token)
	if errNum > 0 {
		return nil, errNum
	}
	o := orm.NewOrm()
	err := o.Begin()
	if err != nil {
		beego.Warning("AuthWithWeiXin fail: ", err)
		return nil, utils.ERROR_CODE_SYSTEM_ERROR
	}

	user := getUserByWeiXinInternal(&o, &authUser.Openid)
	user, errNum = createOrUpdateUserInternal(&o, user, authUser, "AuthWithWeiXin fail: ",
		utils.SNS_PLATFORM_WEIXIN)
	if errNum > 0 {
		o.Rollback()
		return nil, errNum
	}
	err = o.Commit()
	if err != nil {
		beego.Warning("AuthWithWeiXin fail: commit fail ", err)
		o.Rollback()
		return nil, utils.ERROR_CODE_SYSTEM_ERROR
	}

	return user, 0
}

示例#30
文件: models.go 项目: 443752009/go-web-foundation

func AddTopic(title, category, lable, content, attachment string) error {
	// 处理标签
	lable = "$" + strings.Join(strings.Split(lable, " "), "#$") + "#"

	o := orm.NewOrm()

	topic := &Topic{
		Title:      title,
		Category:   category,
		Lables:     lable,
		Content:    content,
		Attachment: attachment,
		Created:    time.Now(),
		Updated:    time.Now(),
	}
	_, err := o.Insert(topic)
	if err != nil {
		return err
	}

	// 更新分类统计
	cate := new(Category)
	qs := o.QueryTable("category")
	err = qs.Filter("title", category).One(cate)
	if err == nil {
		// 如果不存在我们就直接忽略,只当分类存在时进行更新
		cate.TopicCount++
		_, err = o.Update(cate)
	}

	return err
}

展开阅读全文