Skip to content

Update方法

Tuuz edited this page Apr 3, 2026 · 6 revisions

普通update方法

func Api_update_img(id, img interface{}) bool {
	db := tuuz.Db().Table(Table)
	where := map[string]interface{}{
		"id": id,
	}
	db.Where(where)
	data := map[string]interface{}{
		"img": img,
	}
	db.Data(data)
	_, err := db.Update()
	if err != nil {
		Log.Dbrr(err, tuuz.FUNCTION_ALL())
		return false
	} else {
		return true
	}
}

事务update方法

这里外部调用的方法参考Insert部分,记得调用的时候要注入Db连接,不然Db就是nil的状态,你也可以在方法里面加入一个没有传入就自动创建的判断,但是不建议,因为虽然这样看似不会出错,但是如果在项目后期这些调用方法被遗忘,则有可能出现需要注入Db的地方忘记注入导致脏读脏写脏更新后患无穷,所以这里建议不要直接写,养成良好习惯并且在编程测试阶段就把这类问题干掉,降低后期需要debug自己记忆的难度是后期也能继续顺利推进项目的关键!

type Interface struct {
	Db gorose.IOrm
}

func (self *Interface) Api_update_img(id, parent_id, img interface{}) bool {
	db := self.Db.Table(Table)
	where := map[string]interface{}{
		"id":        id,
		"parent_id": parent_id,
	}
	db.Where(where)
	data := map[string]interface{}{
		"img": img,
	}
	db.Data(data)
	_, err := db.Update()
	if err != nil {
		Log.Dbrr(err, tuuz.FUNCTION_ALL())
		return false
	} else {
		return true
	}
}

金融类型项目(带锁)

这里给一个demo,没有输出,还记得你在Find或者Get方法里面做了db.LockForUpdate()动作吗?update这个方法给大家返回了int64以及error两个参数,err就不必多说了,int64返回的是“受影响的行数”,举个例子,例如原来数据库里面id=1的这行的balance字段是0,那么第一次执行将balance更新为“1”的时候“this_will_return_affect_row”就会返回1,当你再次执行的时候就会返回“0”,能理解吗?因为第一次执行的时候,balance从0变成1,所以这一行受影响了,所以会返回1,第二次执行,balance从1变成1因为已经是1了所以不成立,所以mysql就不会去改数据,所以这里就会是0,这个数据是由数据库返回的,注意,没有修改并不算出错,所以即使没有修改,这里的err也会是nil,所以如果你需要对“动作成功与否”进行判断则需要额外加入this_will_return_affect_row的判断最后输出,输出方法同上

type Interface struct {
	Db gorose.IOrm
}

func (self *Interface) Api_update() {
	db := self.Db.Table("mt_balance")
	db.Where("id", "1")
	this_will_return_affect_row, err := db.Update(map[string]any{"balance": 1})
	fmt.Println(this_will_return_affect_row, err)
}

Clone this wiki locally