1

I have MySQL table with json field:

Schema::create('meta', function (Blueprint $table) {
       $table->json('details');
});

and array of key and values:

$filter = ['key' => 'val', 'id' => 'val'];

How to select rows where json containing keys and values from array?

This don't works:

Meta::where('details', $filter)->get();
Meta::whereJsonContains('details', $filter)->get();

Any ideas?

1

2 Answers 2

2

Workaround:

Meta::where(function($query) use($filter) {
    foreach($filter as $k => $v) {
        $query->orWhere("details->{$k}", $v);
    }
})->get();

But it will not work with deep nested arrays.

Sign up to request clarification or add additional context in comments.

Comments

1

You need to use JSON Where Clauses

To query a JSON column, use the -> operator:

$users = DB::table('users')
                ->where('options->language', 'en')
                ->get();

$users = DB::table('users')
                ->where('preferences->dining->meal', 'salad')
                ->get();

5 Comments

I know this, the problem is different. Re-read the question again.
Is it deeply nested?
I don't know the names of the keys and their depth, I just have an array with some keys and values.
I think your own answer is the best one for this solution. As for the deep nesting issue you can make it into a recursive function. Otherwise I think re-thinking your database design is the best option. :)
It is strange that such a possibility is not built into the Eloquent. For non-json-wheres such is out of the box.

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.