0

I have category table with tree structures and products table. I want to show on listing. when user click parent category I want to show all products of this category and products of sub-category of this category too.

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

    }

debug of $catarray is

[
    (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
]

Errors :Notice (8): Undefined variable: catarray [APP/Controller\CategoriesController.php, line 81]
Errors : Impossible to generate condition with empty list of values for field (categories_id)

Cœur
  • 37,241
  • 25
  • 195
  • 267
Ye Htun Z
  • 2,079
  • 4
  • 20
  • 31
  • 4
    That notice is caused by it not being passed to the anonymous function. See http://stackoverflow.com/questions/11420520/php-variables-in-anonymous-functions – Sevvlor Jan 28 '16 at 09:13

1 Answers1

0

as stated by Sevvlor you have to do

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

but you can also simplify your code doing:

$categoryid=$this->Categories->find('children',['for'=>$catid]);
$catarray = $categoryid->extract('categoryId');
$products=$this->Products->find()
    ->where(['category_id IN' => $catarray]);
arilia
  • 9,373
  • 2
  • 20
  • 44