互动
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.

67 lines
1.9 KiB

package models
import (
"fmt"
"reflect"
"strings"
"github.com/ouxuanserver/osmanthuswine/src/core"
"github.com/xormplus/xorm"
)
func Condition(condition map[string]interface{}) *xorm.Session {
session := core.GetXormAuto().NewSession()
for k, v := range condition {
if strings.Contains(k, " not in") {
session = session.NotIn(strings.TrimRight(k, " not in"), v)
} else if strings.Contains(k, " in") {
session = session.In(strings.TrimRight(k, " in"), v)
} else if strings.HasPrefix(strings.ToLower(k), "order by") {
session = session.OrderBy(v.(string))
} else if strings.HasSuffix(k, "<") || strings.HasSuffix(k, ">") ||
strings.HasSuffix(k, "<=") || strings.HasSuffix(k, ">=") ||
strings.HasSuffix(k, "<>") || strings.HasSuffix(k, "=") ||
strings.HasSuffix(k, "!=") {
session = session.Where(fmt.Sprintf("%s?", k), v)
} else {
session = session.Where(fmt.Sprintf("%s=?", k), v)
}
}
return session
}
func Save(condition map[string]interface{}, obj interface{}, filed ...string) error {
session := Condition(condition)
defer session.Close()
if condition != nil && Exit(session.Clone(), reflect.New(reflect.TypeOf(obj).Elem()).Interface()) {
//存在则更新
_, err := session.Cols(filed...).Update(obj)
return err
} else {
//不存在则插入
_, err := session.InsertOne(obj)
return err
}
}
func Exit(session *xorm.Session, obj interface{}) (result bool) {
defer session.Close()
result, _ = session.Exist(obj)
return result
}
func GetTableName(bean interface{}) string {
if table, ok := bean.(string); ok {
return table
}
return core.GetXormAuto().TableInfo(bean).Name
}
func AliasTableName(bean interface{}, alias string) string {
tn := GetTableName(bean)
return fmt.Sprintf("%s as %s", tn, alias)
}
func GetById(bean interface{}, id int64) (bool, error) {
return core.GetXormAuto().Where("is_delete=0 and id=?", id).Get(bean)
}