返回顶部
首页 > 资讯 > 后端开发 > GO >GORM golang SQL 查询执行不区分大小写的搜索不起作用
  • 757
分享到

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

2024-02-05 22:02:52 757人浏览 独家记忆
摘要

问题内容 我想在 golang 中进行不区分大小写的搜索。我正在使用这个库。 我已尝试以下方法,但不起作用。 someId = "abc" model := abcModel{Id:

问题内容

我想在 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  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  ae30e377 100 7da0e618-7393-45c2-94dc-5e7b1d6c1610 abc 2023-10-30 10:00:57.774906 -0700 PDT}

因此,您的原始代码似乎可以工作,只是您的错误可能与 p 的定义方式有关

以上就是GORM golang sql 查询执行不区分大小写的搜索不起作用的详细内容,更多请关注编程网其它相关文章!

您可能感兴趣的文档:

--结束END--

本文标题: GORM golang SQL 查询执行不区分大小写的搜索不起作用

本文链接: https://www.lsjlt.com/news/561104.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作