2016-08-13 8 views
1

私はCakePHP 3でhasMany関係のデータを取得するのに苦労しています。私は基本的なフォーラムで作業しています。私の現在の問題はカテゴリとトピックの関係です。カテゴリには複数のトピックが含まれ、各トピックは1つのカテゴリに属します。カテゴリとトピックの両方について、私はベークメカニズムを使用し、テーブルとの関係を追加しました。これは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); 
} 
関連する問題