简体   繁体   中英

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?

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();

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",
    }
    ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM