2016-11-11 81 views
0

我是CakePHP的新手(使用版本3)。我完成了Cake的博客教程,并试验了一些自定义。有一个让我难以理解的是将一个Category列添加到Articles表中。我可以添加类别ID,但我更喜欢类别名称。CakePHP:使用外键在视图中显示相关数据

我建立了一个 “属于” 的文章模型关系:

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

我也使用的设定()方法在文章控制器类:

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'] 

虽然这只是留下一个空的列。我究竟做错了什么?

P.S.我发现了一个类似(但没有答案)的问题在这里:

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

+1

可以告诉你的$调试值的指数函数中的物品?尝试调试($ articles);在索引函数中,并发布什么.. –

+1

@Jacek已经显示了如何在这种情况下做到这一点。 @Manohar提供了一个有用的提示,以便在遇到这种问题时如何解决这类问题;让'debug'和'pr'成为你最好的朋友! –

+0

谢谢,Manohar和Greg!事后看来很明显,我没有想过使用调试功能。对于像我一样可以从一些Cake调试知识中受益的人,这里有一个方便的链接: http://book.cakephp.org/3.0/en/development/debugging.html –

回答

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

Controller/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

+0

谢谢Jacek!那就是诀窍。我曾看过关联的Cake页面,但在控制器和视图方面似乎有些短暂。现在我已经看到了您的解决方案,它看起来像是我缺少的: http://book.cakephp.org/3.0/en/controllers/components/pagination.html#joining-additional-associations –