com.snow.auto_monitor/app/models/merchant/merchant.go

119 lines
2.7 KiB
Go
Raw Normal View History

2024-07-12 18:11:21 +08:00
package merchant
import (
"sync"
"time"
"github.com/qit-team/snow-core/db"
)
var (
once sync.Once
m *merchantModel
)
/**
* Merchant
*/
type Merchant struct {
2024-07-15 15:45:09 +08:00
Id int64 `xorm:"pk autoincr"` //注使用getOne 或者ID() 需要设置主键
Name string
PrivateKey string
CreatedAt time.Time `xorm:"created"`
2024-07-12 18:11:21 +08:00
}
/**
* 表名规则
* @wiki http://gobook.io/read/github.com/go-xorm/manual-zh-CN/chapter-02/3.tags.html
*/
func (m *Merchant) TableName() string {
return "merchant"
}
/**
* 私有化防止被外部new
*/
type merchantModel struct {
db.Model //组合基础Model集成基础Model的属性和方法
}
// 单例模式
func GetInstance() *merchantModel {
once.Do(func() {
m = new(merchantModel)
//m.DiName = "" //设置数据库实例连接默认db.SingletonMain
})
return m
}
/**
* 查询主键ID的记录
* @param id 主键ID
* @return has 是否有记录
* @return err 错误信息
* @return merchant 查询结果
*/
func (m *merchantModel) GetById(id int64) (merchant *Merchant, has bool, err error) {
merchant = &Merchant{}
has, err = m.GetDb().ID(id).Get(merchant)
2024-07-15 14:42:48 +08:00
if err != nil || !has {
2024-07-12 18:11:21 +08:00
merchant = nil
}
return
}
func (m *merchantModel) Search(id int64, name string, startTime string, endTime string, limit int, page int) (merchant []*Merchant, err error) {
merchant = make([]*Merchant, 0)
sql := "1=1"
var args []interface{}
if id != 0 {
sql += " and id = ?"
args = append(args, id)
}
if name != "" {
sql += " and name = ?"
args = append(args, name)
}
if startTime != "" && endTime != "" {
sql += " and created_at >= ? and created_at <= ?"
args = append(args, startTime, endTime)
}
2024-07-18 15:40:32 +08:00
err = m.GetDb().Where(sql, args...).OrderBy("created_at desc").Limit(limit, page).Find(&merchant)
2024-07-12 18:11:21 +08:00
return
}
func (m *merchantModel) CountAll(id int64, name string, startTime string, endTime string) (res int64, err error) {
sql := "1=1"
var args []interface{}
if id != 0 {
sql += " and id = ?"
args = append(args, id)
}
if name != "" {
sql += " and name = ?"
args = append(args, name)
}
if startTime != "" && endTime != "" {
sql += " and created_at >= ? and created_at <= ?"
args = append(args, startTime, endTime)
}
res, err = m.GetDb().Table("merchant").Where(sql, args...).Count()
return
}
func (m *merchantModel) Create(merchant *Merchant) (affected int64, err error) {
2024-07-16 09:32:37 +08:00
merchant.CreatedAt = time.Now()
2024-07-12 18:11:21 +08:00
affected, err = m.GetDb().Insert(merchant)
return
}
func (m *merchantModel) Update(merchant *Merchant) (affected int64, err error) {
affected, err = m.GetDb().ID(merchant.Id).Update(merchant)
return
}
func (m *merchantModel) Delete(id int64) (affected int64, err error) {
affected, err = m.GetDb().ID(id).Delete(&Merchant{})
return
}