2017-04-30 107 views
0

我有問題map收集available密鑰。Laravel收集使用地圖,幷包含

available鍵使用contains方法。如果$ unavailableProducts中產品ID的值不包含在$ products中,它應該返回true ($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; 
     }), 
    ]; 
}); 
+1

確定'$ unavailableProducts [ '結果' ]'是一個集合?如果沒有,就把它包裝起來:'collect($ unavailableProducts ['result'])'' – Ohgodwhy

回答

1

首先,確保$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