CakePHP:使用外键在视图中显示相关数据

时间:2016-11-11 21:55:25

标签: php mysql cakephp-3.0

我是CakePHP的新手(使用版本3)。我完成了Cake的博客教程并且一直在尝试一些自定义。让我难过的是将一个Category列添加到Articles表中。我可以添加类别ID,但我更喜欢类别名称。

我设置了一个"属于"文章模型中的关系:

class ArticlesTable extends Table

{

public function initialize(array $config)
{
    parent::initialize($config);
    $this->table('articles');
    $this->displayField('title');
    $this->primaryKey('id');
    $this->addBehavior('Timestamp');
    $this->belongsTo('Categories', [
        'foreignKey' => 'category_id',
    ]);
}

我还对Article控制器中的类别使用了set()方法:

    public function index()
{
    $articles = $this->paginate($this->Articles);
    $this->set(compact('articles'));
    $this->set('_serialize', ['articles']);
    $this->set(compact('categories'));
}

这是我在文章索引视图中的内容:

<?php foreach ($articles as $article): ?>
        <tr>
            <td>
                <?= $article->category_id ?>
            </td>
            <td>...

我尝试更换&#34; $ article-&gt; category_id&#34;有一些不同的东西,但没有成功。我最好的猜测如下:

$article['Categories']['id']

但是,这只留下一个空列。我做错了什么?

P.S。我在这里找到了类似的(但没有答案)问题:

How to find field through foreign key in cakephp3.x.x?

1 个答案:

答案 0 :(得分:1)

<强>模型/表/ ArticlesTable.php

class ArticlesTable extends Table
{
    public function initialize(array $config)
    {
        ...
        $this->belongsTo('Categories', [
            'foreignKey' => 'category_id',
        ]);
        ...
    }
    ...
}

型号/表/ CategoriesTable.ph p

class CategoriesTable extends Table
{
    public function initialize(array $config)
    {
        ...
        $this->hasMany('Articles', [
            'foreignKey' => 'category_id',
        ]);
        ...
    }
    ...
}

<强>控制器/ ArticlesController.php

public function index()
{
    $this->paginate = [
        'contain' => ['Categories']
    ];

    $articles = $this->paginate($this->Articles);

    $this->set(compact('articles'));
    $this->set('_serialize', ['articles']);
}

<强>模板/文章/ index.ctp

<?php foreach ($articles as $article): ?>
    <tr>
        <td>
            <?= $article->category->name ?>
        </td>
     <td>
<?php endforeach; ?>

Here you can read more about Associations