1

i want query a table with a json column the object stored in json column is like this:

[    
    {
        "title":"first",
        "ids":[79,583,584]
    },
    {
        "title":"second",
        "ids":[600,601,602]
    },
    {
        "title":"third",
        "ids":[605,606,624]
    }
]

and for example i want to find a row where one of its ids property contain for example 79. something like this:

Model::query()->whereJsonContains('data', ['ids[*]' => 79])->first();

i,ve searched a lot and tried some syntaxes but nothing worked. is that possible to do? how? my database is mysql

1

1 Answer 1

1

querying nested json formats might not be available as of now, you can try filtering the eloquent collection though.

you have to cast the json data column as array on your model first and then filter the collection as per your conditions.

$id = 8;
$filtered = Model::all()->filter(function($item, $key) use($id) {
    $count = 0;
    foreach($item->data as $data) {
        if(in_array($id, $data['ids'])) {
            $count += 1;
        }
    }
    return $count > 0;
})->all();
Sign up to request clarification or add additional context in comments.

Comments

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.