Laravel使用地图收集并包含 [英] Laravel collection using map and contains
问题描述
我在map
集合中的available
键上遇到问题.
I am having problem with available
key in the map
collection.
available
键使用contains
方法.如果$ unavailableProducts中产品ID的值不包含在$ products ($value->product_id == $product->id)
The available
key use contains
method. It should return true if the value of product id in $unavailableProducts does not contain in $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;
}),
];
});
推荐答案
首先,确保$unavailableProductions['result']
是集合.
第二,像这样更改您的contains
方法:
Second, change your contains
method like this:
$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
The $unavailableProducts['result']->contains('id', $product->id)
will determine if the $unaviableProductions['result']
collection has a key id
where the value is $product->id
这篇关于Laravel使用地图收集并包含的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!