卓越飞翔博客卓越飞翔博客

卓越飞翔 - 您值得收藏的技术分享站
技术文章34055本站已运行391

GORM golang SQL 查询执行不区分大小写的搜索不起作用

gorm golang sql 查询执行不区分大小写的搜索不起作用

问题内容

我想在 Golang 中进行不区分大小写的搜索。我正在使用这个库。

我已尝试以下方法,但不起作用。

someId = "abc"
model := abcModel{Id: someId}
result := p.db.Where("lower(id) = lower(?)", someId).Take(&model)

Id is primary-key here

我也尝试过

db.Where("LOWER(id) LIKE LOWER(?)", fmt.Sprintf("%%%s%%", someId)).Take(&model)

有人可以帮忙吗?不确定出了什么问题。任何指示将不胜感激。

谢谢!

<小时/>

编辑

这就是我在数据库中拥有的内容

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

我希望上面的查询会在数据库中返回这条记录,因为它是不区分大小写的搜索。

我收到的错误是 record not found https://gorm.io/docs/error_handling.html#ErrRecordNotFound

我正在 Docker 容器中运行 Postgres 服务器。 https://hub.docker.com/_/postgres


正确答案


尚不清楚 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 的定义方式有关

卓越飞翔博客
上一篇: 添加和使用 Go 模块库次要版本(主要版本 > 2)
下一篇: 返回列表
留言与评论(共有 0 条评论)
   
验证码:
隐藏边栏