1
votes

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?

2

2 Answers

2
votes

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

0
votes

Thanks to bill for the hint. Here's my view method in the categories controller:

public function view($id = null) {
    $category = $this->Categories->get($id, [
        'contain' => []
    ]);

    $this->set('category', $category);
    $this->set('_serialize', ['category']);

    $topics = $this->Categories->Topics->find()->where(['category' => $id]);
    $this->set('topics', $topics);
}