想要在cakephp 3中获得子类别产品

问题描述 投票:0回答:1

我有树结构和产品表的类别表。我想在列表上显示。当用户点击父类别时,我想要显示此类别的所有产品以及此类别的子类别的产品。

 public function listing($catid = null, $slug = null)
    {
        $this->viewBuilder()->layout('frontview');
        $this->loadModel('Categories');
        $this->loadModel('Products');        
        $categoryid=$this->Categories->find('children',['for'=>$catid]);
        $catarray=array();
        foreach($categoryid as $c) {
            $catarray[]=$c['categoryId'];
        }
        debug($catarray);
        $products=$this->Products->find()
            ->where(function ($exp, $q) {
        return $exp->in('categories_id',$catarray); //line 81
    });
       $this->set('products',$products);

    }

$ catarray的调试是

[
    (int) 0 => (int) 6,
    (int) 1 => (int) 7,
    (int) 2 => (int) 8,
    (int) 3 => (int) 9,
    (int) 4 => (int) 10,
    (int) 5 => (int) 11,
    (int) 6 => (int) 12
]

错误:注意(8):未定义的变量:catarray [APP / Controller \ CategoriesController.php,第81行] 错误:无法使用字段值的空列表生成条件(categories_id)

php mysql cakephp
1个回答
0
投票

正如Sevvlor所说,你必须这样做

function ($exp, $q) uses(catarray)

但您也可以简化您的代码:

$categoryid=$this->Categories->find('children',['for'=>$catid]);
$catarray = $categoryid->extract('categoryId');
$products=$this->Products->find()
    ->where(['category_id IN' => $catarray]);
© www.soinside.com 2019 - 2024. All rights reserved.