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();
1
  • 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. Commented Dec 20, 2018 at 23:22

1 Answer 1

7

Use a raw expression to cast the comparison value:

$fff = \App\Cart::whereRaw('features = cast(? as json)', json_encode($features))->get();
Sign up to request clarification or add additional context in comments.

1 Comment

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)")

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.