laravel: JSON Field Comparison with Array

Viewed 1873
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();
1 Answers

Use a raw expression to cast the comparison value:

$fff = \App\Cart::whereRaw('features = cast(? as json)', json_encode($features))->get();
Related