Skip to content

Commit fc4f7e8

Browse files
authored
refactor for searching user (#1038)
* refactor for searching user * fix like bug * better format for builder cond
1 parent 8894f85 commit fc4f7e8

File tree

1 file changed

+13
-11
lines changed

1 file changed

+13
-11
lines changed

models/user.go

Lines changed: 13 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ import (
2323
"unicode/utf8"
2424

2525
"github.com/Unknwon/com"
26+
"github.com/go-xorm/builder"
2627
"github.com/go-xorm/xorm"
2728
"github.com/nfnt/resize"
2829
"golang.org/x/crypto/pbkdf2"
@@ -1235,27 +1236,28 @@ func SearchUserByName(opts *SearchUserOptions) (users []*User, _ int64, _ error)
12351236
opts.Page = 1
12361237
}
12371238

1238-
searchQuery := "%" + opts.Keyword + "%"
12391239
users = make([]*User, 0, opts.PageSize)
1240+
12401241
// Append conditions
1241-
sess := x.
1242-
Where("LOWER(lower_name) LIKE ?", searchQuery).
1243-
Or("LOWER(full_name) LIKE ?", searchQuery).
1244-
And("type = ?", opts.Type)
1242+
cond := builder.And(
1243+
builder.Eq{"type": opts.Type},
1244+
builder.Or(
1245+
builder.Like{"lower_name", opts.Keyword},
1246+
builder.Like{"LOWER(full_name)", opts.Keyword},
1247+
),
1248+
)
12451249

1246-
var countSess xorm.Session
1247-
countSess = *sess
1248-
count, err := countSess.Count(new(User))
1250+
count, err := x.Where(cond).Count(new(User))
12491251
if err != nil {
12501252
return nil, 0, fmt.Errorf("Count: %v", err)
12511253
}
12521254

1255+
sess := x.Where(cond).
1256+
Limit(opts.PageSize, (opts.Page-1)*opts.PageSize)
12531257
if len(opts.OrderBy) > 0 {
12541258
sess.OrderBy(opts.OrderBy)
12551259
}
1256-
return users, count, sess.
1257-
Limit(opts.PageSize, (opts.Page-1)*opts.PageSize).
1258-
Find(&users)
1260+
return users, count, sess.Find(&users)
12591261
}
12601262

12611263
// ___________ .__ .__

0 commit comments

Comments
 (0)