我想在Golang做一个不区分大小写的搜索.我正在使用this号图书馆.

我试过以下几种方法,但都不管用.

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)

谁来帮帮忙好吗.不知道哪里出了问题.如有任何建议,我们将不胜感激.

谢谢!


100:

这就是我在数据库里的东西

         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的方式有关

Postgresql相关问答推荐

PostgreSQL数据文件是否仅在判断点期间写入磁盘?

org.postgresql. util.PSQLException:使用docker + docker—compose + kafka + springboot时try 连接失败

处理Ruust-DIESEL中的Jsonb PostgreSQL列

多克.波斯格雷斯.PgAdmin4

将XML解析从T-SQL迁移到Postgres时出现问题

PostgreSQL 中的 Datum 数据类型是什么以及它的用途是什么?

JOOQ:数据库版本早于 COCKROACHDB 支持的方言:13.0.0

有没有办法使用postgresql将具有不同ID的同一行多次添加到表中?

使用间隔参数的 go postgres 准备好的语句不起作用

Postgres 根据自己的估计 Select 一个更费时的查询计划

timezone date_trunc 函数

?(问号)运算符在 Rails 中查询 Postgresql JSONB 类型

Select 中的 PostgreSQL 正则表达式捕获组

在 PostgreSQL 数组中查找值的位置

如何在 postgres 中使用 json_populate_recordset 解析 json

python postgres 我可以 fetchall() 100 万行吗?

在 Postgres 9.0+ 中使用 PL/pgSQL 在表上循环

判断 Postgres 中是否存在序列(plpgsql)

PostgreSQL - pg_config -bash:pg_config:command not found

如何在 PostgreSQL 中生成一系列重复数字?