peacerokkaz peacerokkaz - 1 year ago 105
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) {



$this->hasMany('Topics', [
'foreignKey' => 'category'

And here's the same for the TopicsTable:

public function initialize(array $config) {



$this->belongsTo('Categories', [
'foreignKey' => 'category'

Now I want to list the topics of one category like this (

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

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

Answer Source

Categories controller:

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download