XORMGoORM
模糊查询忽略大小写基本语法
LOWER
SELECT * FROM table WHERE LOWER(name) like LOWER('%name%');
XORM中使用
wherebuilderSQLbuilder.Cond
where
session.Where("LOWER(name) like LOWER(?)", name)
builder.Like
builder.Likebuilder.LikeWriteTo
builder.Like
// @license xorm.io/builder.Like
import (
"fmt"
"strings"
"xorm.io/builder"
)
// Like defines like condition
type Like [2]string
var _ builder.Cond = Like{"", ""}
// WriteTo write SQL to Writer
func (like Like) WriteTo(w builder.Writer) error {
// 判断是否有使用内置方法
f := "" // 方法名称, e.g. LOWER
s := "" // 方法名的前括号
e := "" // 方法名的后括号
v := like[1]
if i := strings.IndexByte(v, '('); i > -1 && v[len(v)-1] == ')' {
f = v[:i]
s = "("
e = ")"
v = v[i+1 : len(v)-1]
}
if _, err := fmt.Fprintf(w, "%s LIKE %s%s?%s", like[0], f, s, e); err != nil {
return err
}
// FIXME: if use other regular express, this will be failed. but for compatible, keep this
if v[0] == '%' || v[len(v)-1] == '%' {
w.Append(v)
} else {
w.Append("%" + v + "%")
}
return nil
}
// And implements And with other conditions
func (like Like) And(conds ...builder.Cond) builder.Cond {
return builder.And(like, builder.And(conds...))
}
// Or implements Or with other conditions
func (like Like) Or(conds ...builder.Cond) builder.Cond {
return builder.Or(like, builder.Or(conds...))
}
// IsValid tests if this condition is valid
func (like Like) IsValid() bool {
return len(like[0]) > 0 && len(like[1]) > 0
}
用法
session.Where(Like{"LOWER(name)", "LOWER(%"+name+"%)"})
参考