4
laravel-5.7/mysql

In my database, I have a json format field like this:

field name: features:

[
    {"id": 1, "url": null, "name": "A"}, 
    {"id": 2, "url": null, "name": "B"}
]

Also in its model,I wrote this

  protected $casts = [
    'features' => 'array'
  ];

Now I create an array:

$features = array();

temp = array();
temp['id'] = 1;
temp['url'] = null;
temp['name'] = A;
$features[] = temp;

temp = array();
temp['id'] = 2;
temp['url'] = null;
temp['name'] = B;
$features[] = temp;

How can I compare $features array with features field in the database?

ّI checked these:

$fff = \App\Cart::whereFeatures($features)->get()->first();

or

$fff = \App\Cart::whereFeatures(json_encode($features))->get()->first();

or

$fff = \App\Cart::whereFeatures(json_encode($features,JSON_UNESCAPED_UNICODE))->get()->first();
Areza
  • 671
  • 14
  • 26
  • I think before you call `get()` you are working with query builder, so it will maybe be a string comparison with what is in the database column. – miken32 Dec 20 '18 at 23:22

1 Answers1

7

Use a raw expression to cast the comparison value:

$fff = \App\Cart::whereRaw('features = cast(? as json)', json_encode($features))->get();
Jonas Staudenmeir
  • 24,815
  • 6
  • 63
  • 109
  • This really helped me out. and i didn't knew that we can pass a second argument else we have to write like this and it would cause problems with single quotes i guess. `whereRaw("options = CAST('".json_encode($options)."') as JSON)")` – MR_AMDEV Feb 22 '23 at 13:50