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

时间:2016-02-18 12:31:33

标签: yii2 yii2-advanced-app yii2-basic-app

我有2个表格结构如下:

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

我想要做的是当我选择类别(1)电子时 我想得到 三星,索尼,松下表产品

2 个答案:

答案 0 :(得分:3)

因此,您必须在Category模型中调用更多类别的关系函数。另一个调用Products的关系函数。我假设名称是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;
}

答案 1 :(得分:-1)

// 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();

有些对象可以在那里清理数组functionallity。这很快,很脏,但应该有效。你明白了。

相关问题