package model import ( "aps_crm/constvar" "aps_crm/pkg/mysqlx" "errors" "fmt" "gorm.io/gorm" "sync" ) type ( // InvoiceType 发票类型 InvoiceType struct { Id int `json:"id" gorm:"column:id;primary_key;AUTO_INCREMENT"` Name string `json:"name" gorm:"column:name"` } // InvoiceTypeSearch 发票类型搜索条件 InvoiceTypeSearch struct { InvoiceType Orm *gorm.DB QueryClass constvar.InvoiceTypeQueryClass KeywordType constvar.InvoiceTypeKeywordType Keyword string PageNum int PageSize int } ) func (InvoiceType) TableName() string { return "invoice_type" } func NewInvoiceTypeSearch() *InvoiceTypeSearch { return &InvoiceTypeSearch{ Orm: mysqlx.GetDB(), } } func (slf *InvoiceTypeSearch) build() *gorm.DB { var db = slf.Orm.Model(&InvoiceType{}) if slf.Id != 0 { db = db.Where("id = ?", slf.Id) } return db } func (slf *InvoiceTypeSearch) Create(record *InvoiceType) error { var db = slf.build() return db.Create(record).Error } func (slf *InvoiceTypeSearch) CreateBatch(records []*InvoiceType) error { var db = slf.build() return db.Create(records).Error } func (slf *InvoiceTypeSearch) Delete() error { var db = slf.build() return db.Delete(&InvoiceType{}).Error } func (slf *InvoiceTypeSearch) Update(record *InvoiceType) error { var db = slf.build() return db.Updates(record).Error } func (slf *InvoiceTypeSearch) FindAll() ([]*InvoiceType, error) { var db = slf.build() var record = make([]*InvoiceType, 0) err := db.Find(&record).Error return record, err } func (slf *InvoiceTypeSearch) SetId(id int) *InvoiceTypeSearch { slf.Id = id return slf } func (slf *InvoiceTypeSearch) SetOrm(tx *gorm.DB) *InvoiceTypeSearch { slf.Orm = tx return slf } func (slf *InvoiceTypeSearch) First() (*InvoiceType, error) { var db = slf.build() var record = new(InvoiceType) err := db.First(record).Error return record, err } func (slf *InvoiceTypeSearch) Updates(values interface{}) error { var db = slf.build() return db.Updates(values).Error } func (slf *InvoiceTypeSearch) Save(record *InvoiceType) error { if record.Id == 0 { return errors.New("id为空") } var db = slf.build() if err := db.Save(record).Error; err != nil { return fmt.Errorf("save err: %v, record: %+v", err, record) } return nil } func (slf *InvoiceTypeSearch) Find() ([]*InvoiceType, int64, error) { var db = slf.build() var records = make([]*InvoiceType, 0) var total int64 if err := db.Count(&total).Error; err != nil { return records, total, err } if slf.PageNum > 0 && slf.PageSize > 0 { db = db.Limit(slf.PageSize).Offset((slf.PageNum - 1) * slf.PageSize) } err := db.Find(&records).Error return records, total, err } // InitDefaultData 初始化数据 func (slf *InvoiceTypeSearch) InitDefaultData(errCh chan<- error, wg *sync.WaitGroup) { var ( db = slf.Orm.Table(slf.TableName()) total int64 = 0 ) defer wg.Done() if err := db.Count(&total).Error; err != nil { errCh <- err return } if total != 0 { return } records := []*InvoiceType{ {1, "增票6%"}, {2, "增票16%"}, {3, "增票17%"}, } err := slf.CreateBatch(records) if err != nil { errCh <- err return } }