You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

144 lines
2.7 KiB

2 months ago
package models
import (
"fmt"
"gorm.io/gorm"
"product/backend/moo/db"
)
type Label struct {
// body
Title string `gorm:"type:varchar(255)" json:"title"`
Order int `gorm:"" json:"order"`
State bool `gorm:"" json:"state"`
Remark string `gorm:"type:varchar(1023)" json:"remark"`
EntityType string `gorm:"type:enum('competition')" json:"entityType"`
EntityID uint `gorm:"" json:"entityID"`
// basic models
Model
// association
LabelValues []LabelValue `gorm:"foreignKey:LabelID" json:"labelValues"`
}
// methods
func LabelKeyRow(id uint, withLabelValue bool) (Label, error) {
// model
row := Label{}
if err := db.DB.First(&row, id).Error; err != nil {
return row, err
}
// with association
if withLabelValue {
_ = db.DB.Model(&row).Association("LabelValues").Find(&row.LabelValues)
}
return row, nil
}
func LabelKeyRows(pager Pager, withTotal bool, keyword string, entityType string, entityID uint, withLabelValue bool) ([]Label, int64, error) {
// query
query := db.DB.Model(&Label{})
// filter
// EntityType && EntityID
if entityType != "" {
query.Where("entity_type = ?", entityType)
}
if entityType == "competition" {
if entityID != 0 {
query.Where("entity_id = ?", entityID)
}
}
// keyword
if keyword != "" {
query.Where("title LIKE ?", keyword+"%")
}
// fetch total
var total int64
if withTotal {
query.Count(&total)
}
// order
query.Order(fmt.Sprintf("`%s` %s", pager.SortField, pager.SortOrder))
// # offset limit
offset := -1 // 不限制
if pager.PageSize > 0 {
offset = (pager.PageIndex - 1) * pager.PageSize
}
query.Offset(offset).Limit(pager.PageSize)
// select
query.Select("*")
// fetch
var rows []Label
if result := query.Find(&rows); result.Error != nil {
return rows, 0, result.Error
}
// with association
for i, _ := range rows {
if withLabelValue {
_ = db.DB.Model(&rows[i]).Association("LabelValues").Find(&rows[i].LabelValues)
}
}
return rows, total, nil
}
func LabelKeyRowDel(id uint) error {
// db tx
return db.DB.Transaction(func(tx *gorm.DB) error {
// model delete
if result := tx.Delete(&Label{}, id); result.Error != nil {
return result.Error
}
// association delete
return nil
})
}
func LabelKeyRowUpdate(model *Label) error {
// db tx
return db.DB.Transaction(func(tx *gorm.DB) error {
// model update
if result := tx.Updates(&model); result.Error != nil {
return result.Error
}
// association update
return nil
})
}
// default value
const ()
func LabelKeyRowInsert(model *Label) error {
// default value
// db tx
return db.DB.Transaction(func(tx *gorm.DB) error {
// model create
if result := tx.Create(&model); result.Error != nil {
return result.Error
}
// association create
return nil
})
}