如何让所有属于父母的孩子都能说服?

bot*_*min 7 laravel eloquent

在我的数据库中,我有一个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
Run Code Online (Sandbox Code Playgroud)

如果我这样做$SubCategory1->products,我希望它给我产品1-8

如果我这样做$SubSubCategory3->products,我希望它能给我产品9-12

如果我这样做$Category->products,我希望它能给我所有的产品

基本上,我希望该类别能够提供属于它的所有产品

bot*_*min 8

在希望找到一个很好地使用 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
}
Run Code Online (Sandbox Code Playgroud)


Ket*_*ari 6

假设您的模型名称是Category

在类别模型上创建函数

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

在控制器上使用上述方法

$categories = Category::with('children')->where('parent_id',0)->get();
Run Code Online (Sandbox Code Playgroud)

  • 这给出了具有特定父 ID 的类别。我想要直接或间接具有匹配父级的产品 (2认同)

Cer*_*lin 5

请尝试下面的 Has Many Through 关系并发布结果

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

然后您就可以用来$category->products;查找您的产品


小智 5

这种方式非常有效:

class One extends Model {
    public function children()
    {
        return $this->hasMany(self::class, 'parent_id');
    }

    public function grandchildren()
    {
        return $this->children()->with('grandchildren');
    }
}
Run Code Online (Sandbox Code Playgroud)