我怎样才能使所有孩子口才流于父母之下? [英] How do I get all children that fall under a parent in eloquent?
问题描述
在我的数据库中,有一个类别表.类别可以具有父类别,从而使其具有递归关系
In my database, I have a Categories table. Categories can have parent categories, making it a recursive relationship
我也有一个产品表.每个产品都属于一个类别.
I also have a products table. Each product falls under a category.
例如,我有一棵看起来像这样的树:
Say, for example, I have a tree that looks like this:
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
If I do $SubCategory1->products
, I want it to give me Products 1-8
如果我执行$SubSubCategory3->products
,我希望它给我9-12的产品
If I do $SubSubCategory3->products
, I want it to give me products 9-12
如果我做$Category->products
,我希望它能给我所有产品
If I do $Category->products
, I want it to give me all products
基本上,我希望类别给出属于该类别的所有产品
Basically, I want the category to give all products that fall under it
推荐答案
希望找到一个很好地使用Laravel的答案后,我最终放弃了,只写了代码来做自己想做的事情,结果变得更小了比我预期的要好.
After hoping to find an answer that uses Laravel nicely, I ended up giving up and just writing the code to do what I wanted myself, and it ended up smaller than I anticipated.
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
}
这篇关于我怎样才能使所有孩子口才流于父母之下?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!