2016-08-13 57 views
1

我正在努力獲取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> 

如何獲取與當前所選類別相關的所有主題列表?

回答

0

感謝法案的提示。以下是我在類別控制器中的查看方法:

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