CakePHP 3:显示关联数据以及 find('all')

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

我正在研究 CakePHP 3.2。我有两个表 categoriessubcategories,其中 subcategories 与具有外键 category_id.

categories 相关联

我必须使用这两个表构建下拉导航。这样它看起来像这样

-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

为此,这就是我所做的。 在 AppController.php

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

然后在navigation.ctp

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

但这只打印 category->title 而不是 subcategories

我必须在每个所属类别下打印子类别。

确保在模型中定义关联。

类别模型:

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

子类别型号:

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

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

您的 navigation.ctp 代码段中有错字,

echo $menu_cateory->title;

此外,请确保您已在类别中正确设置 $containedModels,已在类别和子类别中正确设置 hasManybelongsTo 关联,并且您已正确包含 Containable 行为。