Files
lone-services/services/product/internal/model/product_model.go
T
2026-08-25 18:11:28 +08:00

42 lines
996 B
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package model
import (
"lone-services/pkg/modelbase"
"lone-services/services/product/internal/dao"
"gorm.io/gorm"
)
type ProductModel struct {
modelbase.Base
}
func (m ProductModel) TableName() string {
return modelbase.Prefix() + "product"
}
func (m ProductModel) Init() ProductModel {
m.Table = m.TableName()
return m
}
func (m ProductModel) Create(data *dao.ProductCreate) error {
return m.Base.Create(data)
}
// IncrNumber 原子增加库存
func (m ProductModel) IncrNumber(id int64, n uint32) (int64, error) {
ret := modelbase.DB().Table(m.TableName()).
Where("id = ?", id).
Update("number", gorm.Expr("number + ?", n))
return ret.RowsAffected, ret.Error
}
// DecrNumber 原子减少库存(库存不足时 RowsAffected=0
func (m ProductModel) DecrNumber(id int64, n uint32) (int64, error) {
ret := modelbase.DB().Table(m.TableName()).
Where("id = ? AND number >= ?", id, n).
Update("number", gorm.Expr("number - ?", n))
return ret.RowsAffected, ret.Error
}