2016-07-05 71 views
2

在我的數據庫中,我有一個Categories表。類別可以有父類別,使其成爲遞歸關係如何獲得所有屬於父母的孩子?

我也有一個產品表。每個產品屬於一個類別。

說,例如,我有一棵樹,看起來像這樣:

Category 
    Sub-Category 1 
     Sub-Sub-Category 1 
      Product 1 
      Product 2 
      Product 3 
      Product 4 
     Sub-Sub-Category 2 
      Product 5 
      Product 6 
      Product 7 
      Product 8 
    Sub-Category 2 
     Sub-Sub-Category 3 
      Product 9 
      Product 10 
      Product 11 
      Product 12 

如果我做$SubCategory1->products,我希望它給我的產品1-8

如果我做$SubSubCategory3->products,我希望它給我的產品9-12

如果我做$Category->products,我希望它給我的所有產品

基本上,我婉t爲類別,得到其下

+0

你檢查[有很多通(https://laravel.com/docs/5.2/eloquent-relationships#has-many-through)? –

+0

在這個例子中只有2個表格,Has Many如何幫助我? – botmin

+0

也是'Store'類別? – Doom5

回答

1

希望能找到一個使用Laravel很好的答案後,我結束了放棄,只是寫的代碼做什麼,我想我自己,它結束了小比我預想的要多。

public function all_products() 
{ 
    $products = []; 
    $categories = [$this]; 
    while(count($categories) > 0){ 
     $nextCategories = []; 
     foreach ($categories as $category) { 
      $products = array_merge($products, $category->products->all()); 
      $nextCategories = array_merge($nextCategories, $category->children->all()); 
     } 
     $categories = $nextCategories; 
    } 
    return new Collection($products); //Illuminate\Database\Eloquent\Collection 
} 
0

落在所有產品假設你的型號名稱是

類別

控制器上創建的分類模型

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

一個函數中使用上面的方法

$categories = Category::with('children')->where('parent_id',0)->get(); 
+0

這給與一個特定的父母id的類別。 我希望產品直接或間接地擁有匹配的父級 – botmin

0

請嘗試以下有很多通過關係和發佈結果

class Category extends Model 
{ 
    public function products() 
    { 
     return $this->hasManyThrough(
      'App\Product', 'App\Category', 
      'parent_id', 'catergory_id', 'id' 
     ); 
    } 
} 

然後你可以使用$category->products;找到你的產品

+0

,它可以在1層以上起作用,但不在其他任何地方。 [示例](http://i.imgur.com/wy1iJXl.png)。在該截圖中,「托盤」有4個產品,它的父母有12個產品,而父母的父母應該有更多的產品。 – botmin

+0

嘗試記錄生成的查詢以瞭解如何解釋關係信息。 –

相關問題