65 lines
1.2 KiB
Go
65 lines
1.2 KiB
Go
package mysql
|
||
|
||
import (
|
||
"fmt"
|
||
"gitea.party/public-messag-service/config/app_ser/component"
|
||
|
||
"gorm.io/gorm"
|
||
)
|
||
|
||
var (
|
||
Ns9 = component.MySQLClient{}
|
||
)
|
||
|
||
type Model interface {
|
||
TableName() string
|
||
DB() *gorm.DB
|
||
}
|
||
|
||
func GetNs9DB() *gorm.DB {
|
||
return Ns9.DB
|
||
}
|
||
func GetById(m Model, id int) error {
|
||
tx := m.DB().Where("id=?", id).Take(m)
|
||
return tx.Error
|
||
}
|
||
|
||
func Add(m Model) error {
|
||
tx := m.DB().Create(m)
|
||
return tx.Error
|
||
}
|
||
|
||
func Save(m Model, id int, columns []string) error {
|
||
tx := m.DB().Select(columns)
|
||
tx.Where("id=?", id).Updates(m)
|
||
return tx.Error
|
||
}
|
||
|
||
func OrderBySQL(orderBy string, order int, isNullBottom bool) string {
|
||
if orderBy != "" {
|
||
if isNullBottom {
|
||
orderBy = fmt.Sprintf("IF(%s IS NULL, 0, 1) desc, %s", orderBy, orderBy)
|
||
}
|
||
if order == 0 { // 为0倒序,否则升序
|
||
return fmt.Sprintf("%s desc", orderBy)
|
||
} else {
|
||
return fmt.Sprintf("%s asc ", orderBy)
|
||
}
|
||
}
|
||
return ""
|
||
}
|
||
|
||
func GetOrderByStr(by string, order int, isNullBottom bool) string {
|
||
if by != "" {
|
||
if isNullBottom {
|
||
by = fmt.Sprintf("IF(%s IS NULL, 0, 1) desc, %s", by, by)
|
||
}
|
||
if order == 1 { // 为0倒序,否则升序
|
||
return fmt.Sprintf("%s desc ", by)
|
||
} else {
|
||
return fmt.Sprintf("%s asc ", by)
|
||
}
|
||
}
|
||
return ""
|
||
}
|