我正在努力獲取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>
如何獲取與當前所選類別相關的所有主題列表?