Laravel collection using map and contains

2019-05-16 08:44发布

I am having problem with available key in the map collection.

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)

What did I do wrong?

    $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;
        }),
    ];
});

1条回答
再贱就再见
2楼-- · 2019-05-16 09:03

First, make sure that $unavailableProductions['result'] is a collection.

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),
    ];
});

The $unavailableProducts['result']->contains('id', $product->id) will determine if the $unaviableProductions['result'] collection has a key id where the value is $product->id

查看更多
登录 后发表回答