Skip to content

Commit

Permalink
Enhance user search functionality to support ID and keyword searches.…
Browse files Browse the repository at this point in the history
… Updated query conditions to allow searching by user ID alongside username, email, and display name. Improved handling of numeric and string keywords in search queries.
  • Loading branch information
Calcium-Ion committed Jan 6, 2025
1 parent 3f8c12c commit 80fcd4e
Showing 1 changed file with 10 additions and 5 deletions.
15 changes: 10 additions & 5 deletions model/user.go
Original file line number Diff line number Diff line change
Expand Up @@ -134,18 +134,23 @@ func SearchUsers(keyword string, group string, startIdx int, num int) ([]*User,
// 构建基础查询
query := tx.Unscoped().Model(&User{})

// 构建搜索条件
likeCondition := "username LIKE ? OR email LIKE ? OR display_name LIKE ?"

// 尝试将关键字转换为整数ID
keywordInt, err := strconv.Atoi(keyword)
if err == nil {
// 如果转换成功,按照ID和可选的组别搜索用户
// 如果是数字,同时搜索ID和其他字段
likeCondition = "id = ? OR " + likeCondition
if group != "" {
query = query.Where("id = ? AND "+groupCol+" = ?", keywordInt, group)
query = query.Where("("+likeCondition+") AND "+groupCol+" = ?",
keywordInt, "%"+keyword+"%", "%"+keyword+"%", "%"+keyword+"%", group)
} else {
query = query.Where("id = ?", keywordInt)
query = query.Where(likeCondition,
keywordInt, "%"+keyword+"%", "%"+keyword+"%", "%"+keyword+"%")
}
} else {
// 如果不是ID搜索,则使用模糊匹配
likeCondition := "username LIKE ? OR email LIKE ? OR display_name LIKE ?"
// 非数字关键字,只搜索字符串字段
if group != "" {
query = query.Where("("+likeCondition+") AND "+groupCol+" = ?",
"%"+keyword+"%", "%"+keyword+"%", "%"+keyword+"%", group)
Expand Down

0 comments on commit 80fcd4e

Please sign in to comment.