简体   繁体   中英

How to search in a json field that contains an array of objects with Eloquent

I'm trying to seach in JSON field with Eloquent, but now work, seach with 0 results.

This is for Ubuntu server, running PostgresSQL, Laravel 5.8 and Apache 2.

[{
    "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"]);

The query returns empty

PostgreSQL requires the object value to be inside an array:

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

Use a raw expression for case-insensitive search:

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

Have you tried it with a lower-case 'w' in ->whereJsonContains ? Like so:

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

From the documentation , you may have to do something like this:

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

Also, there doesn't appear to be any matching json for your query in the sample you have given in your question - does "Escamonda 2019" appear in your data?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM