Laravel使用地图收集并包含 [英] Laravel collection using map and contains

查看:124
本文介绍了Laravel使用地图收集并包含的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆