【问题标题】:eloquent json where empty雄辩的 json 空
【发布时间】:2021-08-21 16:23:42
【问题描述】:

我需要做的查询是这样的

select `id` ,
json_extract(meta,"$.A") as a,
json_extract(meta,"$.B") as b
 from `C` 
where json_unquote(json_extract(meta, '$."A"'))>
json_unquote(json_extract(meta,'$.B'))

在 workbrench 上运行它会给我 2 个结果

Results
ID   a
414 2000    1500
426 2000    1500

但是当我将它传递给 eloquent 的 orm 时,结果是空的

DB::table('C')->select('meta->A')->
        where('meta->A','>',"json_unquote(json_extract(meta,'$.B'))")->get();

调试库,我发现在 PDO 函数中,它没有正确绑定参数

array:9 [
  "select" => []
  "from" => []
  "join" => []
  "where" => array:1 [
    0 => "json_unquote(json_extract(meta,'$.B'))"
  ]
  "groupBy" => []
  "having" => []
  "order" => []
  "union" => []
  "unionOrder" => []
]


array:1 [
  0 => "json_unquote(json_extract(meta,'$.B'))"
]
"statement bind value"
PDOStatement {#3745
  +queryString: "select json_unquote(json_extract(`meta`, '$."A"')) from `C` where json_unquote(json_extract(`meta`, '$."A"')) > ?"
}

我怎样才能修改它来完成我需要的查询? ,我尝试使用 whereRaw,但我在绑定时遇到了同样的问题

【问题讨论】:

    标签: php mysql pdo eloquent


    【解决方案1】:

    问题很可能是您的原始查询没有使用 mysql 的内置函数,因为实际上不是那么原始(仍在构建中)。

    您可以通过完全删除构建器来使查询成为真正的原始查询,或者更好的是,使用 laravel 本身的 JSON 功能。

    Laravel Queries - JSON where clauses

    类似的东西:

    DB::table('C')->select('meta->A')
        ->whereJsonContains('meta->A', '$.B')
        ->get();
    

    【讨论】:

    • jsoncontains 仅用于查看 B 是否在 A 中,但我想比较 A> B 或 A
    猜你喜欢
    • 2016-05-08
    • 2021-05-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-19
    • 2023-02-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多