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

127 lines
2.8 KiB
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 product
import (
"database/sql"
"sync"
"time"
"github.com/qit-team/snow-core/db"
)
var (
once sync.Once
m *productModel
)
/**
* Product
*/
type Product struct {
Id int64 `xorm:"pk autoincr"` //注使用getOne 或者ID() 需要设置主键
Name string
Price int64
ProductUrl string
Status int64
CreatedAt time.Time `xorm:"created"`
Type int64
ExtendParameter string
QueueNo sql.NullInt64
Spec string
}
/**
* 表名规则
* @wiki http://gobook.io/read/github.com/go-xorm/manual-zh-CN/chapter-02/3.tags.html
*/
func (m *Product) TableName() string {
return "product"
}
/**
* 私有化防止被外部new
*/
type productModel struct {
db.Model //组合基础Model集成基础Model的属性和方法
}
// 单例模式
func GetInstance() *productModel {
once.Do(func() {
m = new(productModel)
//m.DiName = "" //设置数据库实例连接默认db.SingletonMain
})
return m
}
/**
* 查询主键ID的记录
* @param id 主键ID
* @return has 是否有记录
* @return err 错误信息
* @return product 查询结果
*/
func (m *productModel) GetById(id int64) (product *Product, has bool, err error) {
product = &Product{}
has, err = m.GetDb().ID(id).Get(product)
if err != nil || !has {
product = nil
}
return
}
func (m *productModel) Search(id int64, name string, startTime string, endTime string, limit int, page int) (product []*Product, err error) {
product = make([]*Product, 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)
}
err = m.GetDb().Where(sql, args...).OrderBy("created_at desc").Limit(limit, page).Find(&product)
return
}
func (m *productModel) 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("product").Where(sql, args...).Count()
return
}
func (m *productModel) Create(product *Product) (affected int64, err error) {
product.CreatedAt = time.Now()
affected, err = m.GetDb().Insert(product)
return
}
func (m *productModel) Update(product *Product) (affected int64, err error) {
affected, err = m.GetDb().ID(product.Id).Update(product)
return
}
func (m *productModel) Delete(id int64) (affected int64, err error) {
affected, err = m.GetDb().ID(id).Delete(&Product{})
return
}