You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

GORM查询MySQL中JSON布尔字段结果异常问题求助

MySQL下GORM查询JSON布尔属性的异常问题

注:此问题仅在MySQL环境下测试过。

使用布尔参数查询JSON字段内的属性时,查询返回0条数据;但将布尔值直接嵌入WHERE子句时,可返回1条数据。奇怪的是,调试器显示生成的SQL语句完全一致。

结构体定义

results 的类型为 []Account:

type Account struct {
    gorm.Model
    UserID sql.NullInt64
    Number string
    Config AccountConfig `gorm:"type:json;serializer:json"`
}

type AccountConfig struct {
    Enabled bool   `json:"enabled"`
    Foo     string `json:"foo"`
    Bar     int64  `json:"bar"`
}

异常示例

DB.Where("config->'enabled' = ?", true).Find(&results)

对应的SQL日志:

2024/04/30 11:20:10 /__REDACTED__/playground/main_test.go:108
[0.847ms] [rows:0] SELECT * FROM `accounts` WHERE config->'$.enabled' = true

正常示例

DB.Where("config->'enabled' = true").Find(&results)

对应的SQL日志:

2024/04/30 11:20:10 /__REDACTED__/playground/main_test.go:108
[0.647ms] [rows:1] SELECT * FROM `accounts` WHERE config->'$.enabled' = true

补充测试

我还尝试了多种写法,比如使用json_extract和双箭头语法config->>'$.enabled',嵌套值如config->'$.foo.enabled' = true也存在相同问题。

已将该问题提交至GORM仓库的Issue,并在关联的PR中提供了测试用例。

内容的提问来源于stack exchange,提问作者andersryanc

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.25 01:01:06