【问题标题】:CakePHP: Use foreign key to display related data in viewCakePHP:使用外键在视图中显示相关数据
【发布时间】:2016-11-11 21:55:25
【问题描述】:

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

我在 Articles 模型中设置了“属于”关系:

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',
    ]);
}

我还在 Articles 控制器中对类别使用了 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>...

我尝试用一​​些不同的东西替换“$article->category_id”,但没有成功。我的最佳猜测如下:

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

不过,这只会留下一个空列。我做错了什么?

附:我在这里发现了一个类似(但未回答)的问题:

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

【问题讨论】:

  • 你能在你的索引函数中显示 $articles 的调试值吗?尝试调试($articles);在索引函数中并发布那里的内容..
  • @Jacek 已经展示了如何在这种情况下做到这一点。 @Manohar 为您在遇到此类问题时如何解决此类问题提供了有用的提示;让debugpr 成为你最好的朋友!
  • 谢谢,Manohar 和 Greg!虽然事后看来很明显,但我没有想到使用调试功能。对于像我一样可以从一些 Cake 调试知识中受益的其他人,这里有一个方便的链接:book.cakephp.org/3.0/en/development/debugging.html

标签: php mysql cakephp-3.0


【解决方案1】:

模型/表格/ArticlesTable.php

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

模型/表格/CategoriesTable.php

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

【讨论】:

  • 谢谢你,亚采克!那成功了。我在 Associations 上看过 Cake 页面,但在控制器和视图方面似乎有点短。现在我已经看到了您的解决方案,看起来这就是我所缺少的:book.cakephp.org/3.0/en/controllers/components/…
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-06
  • 1970-01-01
  • 2023-03-12
  • 1970-01-01
  • 2021-02-07
相关资源
最近更新 更多