Yii2 查找父类别中的所有产品

Yii2 Find all products in parent category

我有 2 个 table 结构如下:

category(id,cat_name , parent_id);
product(id,category_id ,pro_name);

产品模型中的关系

public function getCategory()
    {
        return $this->hasOne(Category::className(), ['id' => 'category_id']);
    }  

Category

id   cat_name    parent_id
1    Electronic   0
2    Fruit        0
3    TV           1
4    Apple        2

Product
id category_id  pro_name
1  1            Samsung
2  3            Sony
3  3            Panasonic
4  2            Apple
5  2            Orange

我想做的是当我 select 类别 (1) 电子 我想得到 来自 table 产品

的三星、索尼、松下
// given $id is your current toplevel category
$cat_ids = Category::find()->select('id')->where(['parent_id' => $id])->asArray()->all();
$ids = [];
foreach($cat_ids as $value)
{
    $ids[] = $value['id'];
}
$ids = implode(',',$ids);
$categories = Products::find()->where('category_id IN ('.$ids.','.$id.')')->all();

一些反对您可能能够清理的阵列功能。这是快速和肮脏的,但应该工作。你明白了。

因此,您的 Category 模型中必须有一个调用更多类别的关系函数。另一个关系函数调用产品。我假设名称是 getParentId()getProducts()。 (如果你没有,你可以使用 Gii 为你生成它们)

这是您可以在 Category 模型中执行的递归方法:

public function getSubCategories()
{
    if ($categories = $this->parentId) { // the name of your relational function.   
        foreach ($this->parentId as $sub) {
            $categories = array_merge($categories, $sub->subCategories);
        }
    }

    return $categories;
}

public function getProductsWithSubcategories()
{
    $products = $this->products; // the name of your relational function.   

    foreach ($this->subCategories as $sub) {
        $products = array_merge($products, $sub->products);
    }

    return $products;
}