【问题标题】:How to search in a json field that contains an array of objects with Eloquent如何使用 Eloquent 在包含对象数组的 json 字段中进行搜索
【发布时间】:2019-10-04 20:56:51
【问题描述】:

我正在尝试使用 Eloquent 在 JSON 字段中搜索,但现在可以使用,搜索结果为 0。

这适用于运行 PostgresSQL、Laravel 5.8 和 Apache 2 的 Ubuntu 服务器。

[{
    "value": "1",
    "label": "numero"
},{
    "value": "2016",
    "label": "anio"
},{
    "value": "Acer",
    "label": "especie"
},{
    "value": "2",
    "label": "cant_plantar"
}]
PlanificacionInfo::select('datos_complementarios')->WhereJsonContains('datos_complementarios', ["value" => "Escamonda 2019"]);

查询返回空

【问题讨论】:

    标签: json laravel postgresql eloquent


    【解决方案1】:

    您是否尝试过在->whereJsonContains 中使用小写“w”?像这样:

    PlanificacionInfo::select('datos_complementarios')
        ->whereJsonContains('datos_complementarios', ["value" => "Escamonda 2019"]);
    

    documentation,您可能需要执行以下操作:

    $users = PlanificacionInfo::select('datos_complementarios')
            ->whereJsonContains('datos_complementarios->value', 'YOUR SEARCH TERM HERE')
            ->get();
    

    此外,在您在问题中提供的示例中,您的查询似乎没有任何匹配的 json - “Escamonda 2019”是否出现在您的数据中?

    【讨论】:

    • 同样的结果。是的,数据中存在“Escamonda 2019”,JSON是从数据库中提取的。
    【解决方案2】:

    PostgreSQL 要求对象值在数组中:

    PlanificacionInfo::select('datos_complementarios')
        ->whereJsonContains('datos_complementarios', [["value" => "Escamonda 2019"]]);
    

    使用原始表达式进行不区分大小写的搜索:

    PlanificacionInfo::select('datos_complementarios')
        ->whereJsonContains(
            DB::raw('lower("datos_complementarios"::text)'),
            [["value" => strtolower("Escamonda 2019")]]
        );
    

    【讨论】:

    • 它的工作,但我需要让它忽略大小写,我该怎么做?
    • 我还有一个问题要问你,如何在不输入完整值的情况下使用它进行搜索,例如“Escamonda 201”?谢谢
    • 我很确定 PostgreSQL 不支持。
    • 你将如何在 mysql 中运行它?它给出了错误 Unknown column 'lower("datos_complementarios"::text)'
    • @GotaloveCode 整个错误信息是什么?
    猜你喜欢
    • 2020-05-08
    • 2020-05-21
    • 1970-01-01
    • 2020-12-16
    • 2018-06-09
    • 1970-01-01
    • 2012-01-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多