我有 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) 电子 我想要得到 三星,索尼,松下从表产品
因此,您的
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;
}
// 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();
您可能能够清理一些对数组功能的反对。这又快又脏,但应该可行。你明白了。