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

时间:2016-01-28 08:59:31

标签: php mysql cakephp

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

 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)的空值列表生成条件

1 个答案:

答案 0 :(得分: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]);