Laravel whereIn的whereJson包含的实现 [英] Laravel whereIn implementation of whereJsonContains
问题描述
我有这段代码可以正常工作并返回1个项目集合:
I have this code that works fine and returns 1 item collection:
$myCollection = MyModel::whereJsonContains('payload->ProductCode->id', "1")->get();
但是,我不仅要获取$ 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的whereJson包含的实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!