【问题标题】:How to list objects in a hasMany relation in CakePHP 3?如何在 CakePHP 3 中列出 hasMany 关系中的对象?
【发布时间】:2016-08-13 23:34:56
【问题描述】:

我正在努力获取 CakePHP 3 中的 hasMany 关系的数据。我在一个基本论坛上工作,我目前的问题是类别和主题之间的关系。一个类别包含多个主题,而每个主题属于一个类别。对于类别和主题,我使用了烘焙机制并将关系添加到表中。这是 CategoriesTable 类的初始化方法:

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>

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

【问题讨论】:

    标签: php cakephp cakephp-3.0


    【解决方案1】:

    类别控制器:

    $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

    【讨论】:

      【解决方案2】:

      感谢比尔的提示。这是我在类别控制器中的视图方法:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-04-19
        • 1970-01-01
        相关资源
        最近更新 更多