Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel whereIn implementation of whereJsonContains

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?

like image 252
mykoman Avatar asked Oct 23 '25 22:10

mykoman


1 Answers

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();
like image 95
Dilip Hirapara Avatar answered Oct 25 '25 12:10

Dilip Hirapara



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!