問題描述
我有這段代碼可以正常工作并返回 1 個(gè)項(xiàng)目集合:
I have this code that works fine and returns 1 item collection:
$myCollection = MyModel::whereJsonContains('payload->ProductCode->id', "1")->get();
但是,我不僅要在值為 1 時(shí)獲取 $myCollection,而且要在它包含在多個(gè)數(shù)組項(xiàng)之一中時(shí)獲取它.
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();
更新當(dāng)我嘗試此代碼時(shí),它返回一個(gè)空數(shù)據(jù).我的意思是當(dāng)我使用 1 而不是 1" 時(shí).這可能是我使用數(shù)組時(shí)它不起作用的原因嗎?
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",
}
}
運(yùn)行上面的代碼返回一個(gè)空數(shù)據(jù).請(qǐng)問我該如何解決?
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();
這篇關(guān)于Laravel whereIn whereJsonContains 的實(shí)現(xiàn)的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!