PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, January 25, 2022

[FIXED] CakePHP 3 : show associated data along with find('all')

 January 25, 2022     associations, cakephp, cakephp-3.2     No comments   

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
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing