【发布时间】:2016-08-13 23:34:56
【问题描述】:
我正在努力获取 CakePHP 3 中的 hasMany 关系的数据。我在一个基本论坛上工作,我目前的问题是类别和主题之间的关系。一个类别包含多个主题,而每个主题属于一个类别。对于类别和主题,我使用了烘焙机制并将关系添加到表中。这是 CategoriesTable 类的初始化方法:
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>
如何获取与当前所选类别相关的所有主题列表?
【问题讨论】:
标签: php cakephp cakephp-3.0