0

I'm working on CakePHP 3.2. I have two tables categories and subcategories where subcategories is associated with categories with foreign key category_id.

I have to build a drop down navigation using these two tables. So that It will look like this

-Menu
|- Category_1
   |- Category_1_subcategory_1
   |- Category_1_subcategory_2
   |- Category_1_subcategory_3
|- Category_2
   |- Category_2_subcategory_1
   |- Category_2_subcategory_2
|- etc

For this this is what I have done. In AppController.php

// set navigation menu
$this->loadModel('Categories');
$menu_categories = $this->Categories->find('all', [
  'contain' => ['Subcategories'],
]);
$this->set('menu_categories', $menu_categories);

Then in navigation.ctp

$foreach($menu_categories as $menu_category):
   echo $menu_category->title;
   foreach($menu_category->Subcategories as $subcategory):
      echo $subcategory->title;
   endforeach;
endforeach;

But this prints only category->title and not subcategories

I have to print subcategories under each belonging category.

Anuj TBE
  • 9,198
  • 27
  • 136
  • 285

2 Answers2

1

There is a typo in your navigation.ctp snippet,

echo $menu_cateory->title;

Also, make sure you've correctly set $containedModels in Categories, that you've correctly set the hasMany and belongsTo associations in Categories and Subcategories, and that you've correctly included the Containable behavior.

Caius
  • 243
  • 1
  • 5
  • what is error in `echo $menu_category->title`. Categories table contains `title` column which I'm printing. and this is printing well – Anuj TBE Jul 13 '16 at 18:44
  • In your snippet you wrote "$menu_cateory", it's missing the letter g. If that's the code directly from your source file then something else is printing it because that is certainly a syntax error. The main point of my comment however is to make sure that you are correctly associating your models. – Caius Jul 13 '16 at 18:51
  • ohh, sorry, The code was not directly from source. It was typed and was just a typing error. – Anuj TBE Jul 13 '16 at 18:56
0

Make sure to define the associations in the models.

Category Model:

$this->hasMany(
   'Subcategory', [
        'className' => 'Subcategory',
        'foreignKey' => 'category_id'
]);

Subcategory Model:

$this->belongsTo(
   'Category', [
        'className' => 'Category',
        'foreignKey' => 'category_id'
]);

http://book.cakephp.org/3.0/en/orm/associations.html

bill
  • 1,646
  • 1
  • 18
  • 27