Reputation: 1905
I have this code that works fine and returns 1 item collection:
$myCollection = MyModel::whereJsonContains('payload->ProductCode->id', "1")->get();
I however want to fetch the $myCollection not just when the value is 1 but when it is contained in one of many array items.
$array = [0 => 1, 1 => 2, 2 => 3];
$myCollection = MyModel::whereJsonContains('payload->ProductCode->id', $array)->get();
UPDATES When I try this code it return an empty data. I mean when I use 1 instead of "1". Could that be the reason why it doesn't work when I use an array?
$myCollection = MyModel::whereJsonContains('payload->ProductCode->id', 1)->get();
A sample of what the payload contains is this. I suppose that could give more clarity to my question:
{
"ProductCode": {
"id": "1",
"name": "My Service",
}
}
Running the above code returns an empty data. How do I fix this please?
Upvotes: 4
Views: 14275
Reputation: 1
You can use the following code that I have written in Eloquent, but you can use Query builder too.
$data= [0 =>"Ulcer", 1 => "cough", 2 => "fever"];
Clinic::where('receptionist_id',$request->recptionist_id)->whereJsonContains('data', $data)->get();
Upvotes: 0
Reputation: 2087
I think the first part of @Dilip's answer is not correct as I had the same issue with whereJsonContains
on laravel 8. It would return empty result if the field is not a JSON array. The second part of his answer solves the issue but doesn't point the problem here.
The whereJsonContains
method is used to query JSON array fields
which in your case, payload->ProductCode->id
is not an array field. That's why you get empty array.
Now as you are looking for rows that the payload->ProductCode->id
contained within your $array
, the whereIn
method is the method you are looking for.
As Laravel document says, "The whereIn
method verifies that a given column's value is contained within the given array". So you code would be like this:
$array = [ 1, 2, 3];
$myCollection = MyModel::whereIn('payload->ProductCode->id', $array)->get();
// $myCollection contains rows that their `payload->ProductCode->id` is contained within [1, 2, 3] array.
You could use whereJsonContains
method if your data was like this:
{
"ProductCode": {
"id": ["1", "2"],
"name": "My Service",
}
...
}
Upvotes: 1
Reputation: 15306
You need to follow your query as below.
$array = [0 => 1, 1 => 2, 2 => 3];
// Eloquent
PaymentTransaction::whereJsonContains('payload->ProductCode->id',$array)->get();;
// or
PaymentTransaction::jsonContains('payload->ProductCode->id', $array)->get();
you can try it as below too.
$array = [0 => 1, 1 => 2, 2 => 3];
$array = array_values(array_map('strval',$array));
PaymentTransaction::where(function ($query) use ($array) {
foreach ($array as $id) {
$query->orWhereJsonContains('payload->ProductCode->id', $id);
}
})->get();
Upvotes: 4