Laravel集合使用地图并包含

时间:2017-04-30 22:21:34

标签: php laravel laravel-5

我在available集合中遇到map密钥问题。

available密钥使用contains方法。如果$ unavailableProducts中的产品ID值不包含在$ products ($value->product_id == $product->id)

中,则应返回true

我做错了什么?

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

2 个答案:

答案 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"
            }
        ]
    }
]