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