我正在努力获取CakePHP 3中hasMany关系的数据。我正在研究一个基础论坛,而我目前的问题是指类别和主题之间的关系。一个类别包含几个主题,而每个主题都属于一个单独的类别。对于我使用烘焙机制的类别和主题,并将关系添加到表格中。这是CategoriesTable类initialize方法:如何在CakePHP 3中列出hasMany关系中的对象?
public function initialize(array $config) {
parent::initialize($config);
$this->table('categories');
$this->displayField('name');
$this->primaryKey('id');
$this->addBehavior('Timestamp');
$this->hasMany('Topics', [
'foreignKey' => 'category'
]);
}
而这里的TopicsTable相同:
public function initialize(array $config) {
parent::initialize($config);
$this->table('topics');
$this->displayField('id');
$this->primaryKey('id');
$this->addBehavior('Timestamp');
$this->belongsTo('Categories', [
'foreignKey' => 'category'
]);
}
现在我想列出这样一个类别(Categories\view.cpt
)的主题:
<h1><?= $category->name ?></h1>
<table>
<?php foreach ($topics as $topic): ?>
<tr>
<td>
<?= $topic->name ?>
</td>
</tr>
<?php endforeach; ?>
</table>
如何获取与当前所选类别相关的所有主题列表?