2016-07-05 80 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

尝试记录生成的查询以了解如何解释关系信息。 –