Home > front end >  JSON column query using laravel builder
JSON column query using laravel builder

Time:12-14

I have a json column in mysql and i am trying query that column using laravel bulider. That column has an array of json object and i want query a Value attribute in that json object.

use Illuminate\Database\Eloquent\Builder;

class SizeFilter
{
    public function filter(Builder $builder, $value): Builder{
    return $builder->whereJsonContains('sizes',[['Value' => $value]]);
}

and my json column structure is

 [{"SizeID":34,"Sku":null,"Value":"10","stock":2},{"SizeID":35,"Sku":null,"Value":"12","stock":0},{"SizeID":36,"Sku":null,"Value":"14","stock":0},{"SizeID":37,"Sku":null,"Value":"16","stock":0},{"SizeID":38,"Sku":null,"Value":"18","stock":0},{"SizeID":32,"Sku":null,"Value":"6","stock":0},{"SizeID":33,"Sku":null,"Value":"8","stock":1}]

CodePudding user response:

What is $value? It must be a string. If it's an integer, the JSON search won't work.

I don't have Laravel, but I tested in the MySQL client:

mysql> set @j = '...'; -- your example JSON

mysql> select json_contains(@j, '{"Value":"10"}');
 ------------------------------------- 
| json_contains(@j, '{"Value":"10"}') |
 ------------------------------------- 
|                                   1 |
 ------------------------------------- 
1 row in set (0.00 sec)

mysql> select json_contains(@j, '{"Value":10}');
 ----------------------------------- 
| json_contains(@j, '{"Value":10}') |
 ----------------------------------- 
|                                 0 |
 ----------------------------------- 

So make sure it's a string:

return $builder->whereJsonContains('sizes',[['Value' => (string) $value]]);
  • Related