repo.go 2.36 KB
Newer Older
hujiebin's avatar
hujiebin committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
package diamond_m

import (
	"git.hilo.cn/hilo-common/resource/mysql"
	"gorm.io/gorm"
	"hilo-user/myerr"
	"strconv"
)

func (diamondAccountDetail *DiamondAccountDetail) PersistentNoInTransactional() error {
	//fixme: 这里有点奇怪, diamondAccount持久化动作在diamondAccountDetail持久化之后,RowsAffected 就一定是0
	txDiamondAccount := diamondAccountDetail.Db.Model(diamondAccountDetail.diamondAccount)
	if diamondAccountDetail.diamondAccount.CheckUpdateCondition() {
		txDiamondAccount = txDiamondAccount.Where(diamondAccountDetail.diamondAccount.GetUpdateCondition())
	}
	if diamondAccountDetail.AddReduce == mysql.ADD {
		//增加
		txDiamondAccount.UpdateColumn("diamond_num", gorm.Expr("diamond_num + ?", diamondAccountDetail.Num))
	} else if diamondAccountDetail.AddReduce == mysql.REDUCE {
		//减少,保证不能扣成负数
		txDiamondAccount.Where("diamond_num >= ?", diamondAccountDetail.Num).UpdateColumn("diamond_num", gorm.Expr("diamond_num - ?", diamondAccountDetail.Num))
	} else {
		myerr.NewSysError("addReduce 枚举错误 value:" + mysql.TypeToString(mysql.Type(diamondAccountDetail.AddReduce)))
	}
	if err := txDiamondAccount.Error; err != nil {
		return myerr.WrapErr(err)
	}
	if txDiamondAccount.RowsAffected == 0 {
		diamondAccountDetail.Log.Errorf("gorm condition update.RowsAffected = 0,AddReduce:%v", diamondAccountDetail.AddReduce)
		return myerr.NewWaring("gorm condition update.RowsAffected = 0")
	}

	//持久化diamondAccountDetail
hujiebin's avatar
hujiebin committed
34 35 36 37
	//if err := model.Persistent(diamondAccountDetail.Db, diamondAccountDetail); err != nil {
	//	return myerr.WrapErr(err)
	//}
	if err := diamondAccountDetail.DB().Table(diamondAccountDetail.TableName()).Save(diamondAccountDetail).Error; err != nil {
hujiebin's avatar
hujiebin committed
38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
		return myerr.WrapErr(err)
	}
	//改变diamondAccount值
	if diamondAccountDetail.diamondAccount == nil {
		return myerr.NewSysError("持久化错误, 模型:DiamondAccountDetail 中没有diamondAccount, DiamondAccountDetail.Id =" + strconv.Itoa(int(diamondAccountDetail.ID)))
	}

	var newDiamondAccount DiamondAccount
	if err := diamondAccountDetail.Db.First(&newDiamondAccount, diamondAccountDetail.diamondAccount.ID).Error; err != nil {
		return myerr.WrapErr(err)
	}

	if newDiamondAccount.DiamondNum < 0 {
		return myerr.NewSysError("diamond_account表中,diamond_num 不能小于0, diamondAccount.id = " + strconv.Itoa(int(newDiamondAccount.ID)))
	}
	return nil
}