2017-09-16 51 views
0

我在Laravel 5.5中有類別和產品 每個產品都有一個類別和類別可以有父類別。我想在展示時獲得一個類別的所有兒童產品。例如:衣服是一個cateogry,並有像襯衫,夾克等子類別,當我點擊衣服類別時,我想顯示所有具有襯衫或夾克類別的產品。 這裏是我的Category.php型號:Laravel關係返回項目兩次

public function children() 
{ 
    return $this->hasMany('App\Category', 'parent_id'); 
} 
public function products() 
{ 
    return $this->hasMany('App\Product'); 
} 

public function getAllProducts() 
{ 
    $products = $this->products; 

    foreach ($this->children as $child) { 
     foreach ($child->products as $product) { 
      $products[] = $product; 
     } 
     } 

    return $products; 
} 

在我來說,我有一個是 「cloth1」, 「cloth2」 和 「shirt1」 三款產品。 「布料1」和「布料2」屬於衣服類別,「襯衫1」屬於衣服子類別的襯衫類別。所以,當我的衣服分類頁面上我想告訴所有的產品(「cloth1」,「cloth2」和「shirt1」) 但在視圖

{{dd($category->getAllProducts())}} 

返回「cloth1」,「cloth2」 「shirt1」,「shirt1」(它將襯衫返回兩次)。任何想法爲什麼以及如何解決這個問題?

編輯:當我嘗試$category->products的衣服類別,它返回「cloth1」和「cloth2」,當我嘗試它放在襯衫類別,它返回「shirt1」只有一次(這是應該的)

+0

是否在'$ this-> products'和$ $ this-> children'上缺少'()'的拼寫錯誤? –

+0

不可以。就我所知,laravel關係是這樣工作的,括號只在函數不返回關係時才需要。 – TheAngelM97

+0

好吧,混淆哈哈,所以可能是因爲'$ products'已經包含一個數組,你只需在循環'$ products []'中再次添加相同的值,也許可以將返回數組重命名爲其他值。試着在循環中使用'dd()來看看它在做什麼。 –

回答

0

我上的使用方法我的問題 功能現在看起來是這樣的:

public function getAllProducts() 
{ 
    $products = $this->products; 

    foreach ($this->children as $child) { 
     foreach ($child->products as $product) { 
      if (!$products->contains($product)) { 
       $products[] = $product; 
      } 
     } 
    } 

    return $products; 
} 

但我仍然不知道爲什麼它返回「shirt1」如果兩次我不使用contains