Issue
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.
Solution
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
Answered By - bill
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.