Laravel whereIn whereJsonContains 的实现 [英] Laravel whereIn implementation of whereJsonContains

查看:81
本文介绍了Laravel whereIn whereJsonContains 的实现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这段代码可以正常工作并返回 1 个项目集合:

I have this code that works fine and returns 1 item collection:

$myCollection = MyModel::whereJsonContains('payload->ProductCode->id', "1")->get();

但是,我不仅要在值为 1 时获取 $myCollection,而且要在它包含在多个数组项之一中时获取它.

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

更新当我尝试此代码时,它返回一个空数据.我的意思是当我使用 1 而不是 1" 时.这可能是我使用数组时它不起作用的原因吗?

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

这篇关于Laravel whereIn whereJsonContains 的实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆