【发布时间】: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']
不过,这只会留下一个空列。我做错了什么?
附:我在这里发现了一个类似(但未回答)的问题:
【问题讨论】:
-
你能在你的索引函数中显示 $articles 的调试值吗?尝试调试($articles);在索引函数中并发布那里的内容..
-
@Jacek 已经展示了如何在这种情况下做到这一点。 @Manohar 为您在遇到此类问题时如何解决此类问题提供了有用的提示;让
debug和pr成为你最好的朋友! -
谢谢,Manohar 和 Greg!虽然事后看来很明显,但我没有想到使用调试功能。对于像我一样可以从一些 Cake 调试知识中受益的其他人,这里有一个方便的链接:book.cakephp.org/3.0/en/development/debugging.html
标签: php mysql cakephp-3.0