提问人:ray an 提问时间:10/30/2023 最后编辑:ray an 更新时间:10/31/2023 访问量:62
用于执行不区分大小写的搜索的 GORM golang SQL 查询不起作用
GORM golang SQL query to do a case-insensitive search is not working
问:
我想在 Golang 中进行不区分大小写的搜索。我正在使用这个库。
我尝试了以下方法,但它不起作用。
someId = "abc"
model := abcModel{Id: someId}
result := p.db.Where("lower(id) = lower(?)", someId).Take(&model)
Id 在这里是主键
我也试过了
db.Where("LOWER(id) LIKE LOWER(?)", fmt.Sprintf("%%%s%%", someId)).Take(&model)
有人可以帮忙吗?不知道出了什么问题。任何指示将不胜感激。
谢谢!
编辑:
这就是我在DB中拥有的
id | created_at | updated_at | deleted_at | client_id | ttl | client_type | token | expires_on
--------------------------------------+-------------------------------+-------------------------------+------------+--------------------------------------+------+--------------------------------------+
ABC | 2023-10-30 16:10:59.614132+00 | 2023-10-30 16:10:59.614132+00 | | ae30e377 | 100 | 7da0e618-7393-45c2-94dc-5e7b1d6c1610 | abc | 2023-10-30 16:27:39.613566+00
我希望上面的查询会在 DB 中返回此记录,因为它是一个不区分大小写的搜索。
我得到的错误是 https://gorm.io/docs/error_handling.html#ErrRecordNotFoundrecord not found
我在 docker 容器中运行 Postgres 服务器。https://hub.docker.com/_/postgres
答:
1赞
richyen
10/31/2023
#1
目前尚不清楚代表什么,但这里有一个同时使用 和 的工作示例:p
Take()
Where().Take()
func main() {
// open connection to postgres
db, err := gorm.Open(postgres.New(...), &gorm.Config{})
if err != nil {
panic("failed to connect database")
}
// Get the row
someId := "abc"
var result abcModel
db.Take(&result, "lower(id) = lower(?)", someId)
// Print the row
fmt.Println(result)
// Find the row using Where
var result2 abcModel
db.Where("lower(id) = lower(?)", someId).Take(&result2)
// Print the row
fmt.Println(result2)
}
输出:
$ go run .
{ABC 2023-10-30 10:00:57.774905 -0700 PDT 2023-10-30 10:00:57.774905 -0700 PDT <nil> ae30e377 100 7da0e618-7393-45c2-94dc-5e7b1d6c1610 abc 2023-10-30 10:00:57.774906 -0700 PDT}
{ABC 2023-10-30 10:00:57.774905 -0700 PDT 2023-10-30 10:00:57.774905 -0700 PDT <nil> ae30e377 100 7da0e618-7393-45c2-94dc-5e7b1d6c1610 abc 2023-10-30 10:00:57.774906 -0700 PDT}
因此,您的原始代码似乎有效,除了您的错误可能与定义方式有关p
评论
0赞
ray an
10/31/2023
所以,我意识到了我所犯的错误。我正在这样做。(我分享的第一个代码片段) 一旦我做了你正在做的事情,它就开始工作正常。model := abcModel{Id: someId}
var result abcModel
评论
someId
LOWER(id) LIKE ?
LOWER(id) LIKE LOWER(?)
strings.ToLower()
p