我在available
集合中遇到map
密钥问题。
available
密钥使用contains
方法。如果$ unavailableProducts中的产品ID值不包含在$ products ($value->product_id == $product->id)
我做错了什么?
$unavailableProducts = $this->unavailableProducts();
$products = $this->products->all();
$allProducts = $products->map(function ($product) use($unavailableProducts) {
return [
'id' => $product->id,
'title' => $product->title,
'available' => $unavailableProducts['result']->contains(function ($value, $key) use ($product) {
if ($value->product_id == $product->id) {
return false;
}
return true;
}),
];
});
答案 0 :(得分:4)
首先,确保$unavailableProductions['result']
是一个集合。
其次,改变你的contains
方法:
$unavailableProducts = $this->unavailableProducts();
$products = $this->products->all();
$allProducts = $products->map(function ($product) use($unavailableProducts) {
return [
'id' => $product->id,
'title' => $product->title,
'available' => $unavailableProducts['result']->contains('id', $product->id),
];
});
$unavailableProducts['result']->contains('id', $product->id)
将确定$unaviableProductions['result']
集合是否包含值为id
的密钥$product->id
答案 1 :(得分:0)
您可以尝试这种方法
$policyPackageDetails = PolicyPackage::where('isactive', '=', 1)->where('id', '=', $pid)
->with('policy_package_details')
->select('id',
'title',
'subtitle',
'shorttitle',
)
->get();
$policyPackageDetails = $policyPackageDetails ->map(function ($item){
return collect([
'id' => $item->id,
'title' => $item->title,
'subtitle' => $item->subtitle,
'short_title' => $item->shorttitle,
'policy_package_details' => $item->policy_package_details->map(function ($details){
return [
'attribute_name' => $details->attname,
'attribute_value' => $details->attvalue,
];
}),
]);
});
这里从关系模型中获取数据,保留并过滤它们,输出将类似于
[
{
"id": 61,
"title": " Health (Platinum)",
"subtitle": "for 1 year",
"short_title": "HL-SHP-1",
"policy_package_details": [
{
"attribute_name": "in",
"attribute_value": "180000"
},
{
"attribute_name": "out",
"attribute_value": "20000"
}
]
}
]