Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/232.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在CakePHP3中列出hasMany关系中的对象?_Php_Cakephp_Cakephp 3.0 - Fatal编程技术网

如何在CakePHP3中列出hasMany关系中的对象?

如何在CakePHP3中列出hasMany关系中的对象?,php,cakephp,cakephp-3.0,Php,Cakephp,Cakephp 3.0,我正在努力获取CakePHP3中hasMany关系的数据。我正在做一个基本的论坛,我现在的问题是关于类别和主题之间的关系。一个类别包含多个主题,而每个主题都属于一个类别。对于类别和主题,我使用了烘焙机制,并将关系添加到表中。这是分类表类的初始化方法: public function initialize(array $config) { parent::initialize($config); $this->table('categories'); $this-&

我正在努力获取CakePHP3中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
):


如何获取与当前选定类别相关的所有主题列表?

类别控制器:

$topics = $this->Category->Topic->find('list', [
    'keyField' => 'id',
    'valueField' => 'Topic.category'
])
->where(['category' => $category]);
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);
}

谢谢比尔的提示。以下是“类别”控制器中的“我的视图”方法:

$topics = $this->Category->Topic->find('list', [
    'keyField' => 'id',
    'valueField' => 'Topic.category'
])
->where(['category' => $category]);
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);
}