peacerokkaz peacerokkaz - 3 months ago 27
PHP Question

How to list objects in a hasMany relation in CakePHP 3?

I'm struggling with getting the data of a hasMany relation in CakePHP 3. I'm working on a basic forum and my current problem refers to the relation between categories and topics. A category contains of several topics, while each topic belongs to one single category. For both the categories and topics I used the bake mechanism and added the relation to the tables. This is the initialize method for the CategoriesTable class:

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'
]);
}


And here's the same for the 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'
]);
}


Now I want to list the topics of one category like this (
Categories\view.cpt
):

<h1><?= $category->name ?></h1>
<table>
<?php foreach ($topics as $topic): ?>
<tr>
<td>
<?= $topic->name ?>
</td>
</tr>
<?php endforeach; ?>
</table>


How do I get the list of all topics related to the currently selected category?

Answer

Categories controller:

$topics = $this->Category->Topic->find('list', [
    'keyField' => 'id',
    'valueField' => 'Topic.category'
])
->where(['category' => $category]);

http://book.cakephp.org/3.0/en/orm/retrieving-data-and-resultsets.html#finding-key-value-pairs

Comments