Issue
I'm new to CakePHP (using version 3). I completed Cake's blog tutorial and have been experimenting with some customizations. One that has me stumped is adding a Category column to the Articles table. I can add the category ID, but I'd prefer the category name.
I set up a "belongs to" relationship in the Articles model:
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',
]);
}
I also used the set() method for categories in the Articles controller:
public function index()
{
$articles = $this->paginate($this->Articles);
$this->set(compact('articles'));
$this->set('_serialize', ['articles']);
$this->set(compact('categories'));
}
Here's what I have in my Articles index view:
<?php foreach ($articles as $article): ?>
<tr>
<td>
<?= $article->category_id ?>
</td>
<td>...
I tried replacing "$article->category_id" with a few different things, but have had no success. My best guess was the following:
$article['Categories']['id']
That just leaves an empty column, though. What am I doing wrong?
P.S. I found a similar (but unanswered) question here:
How to find field through foreign key in cakephp3.x.x?
Solution
Model/Table/ArticlesTable.php
class ArticlesTable extends Table
{
public function initialize(array $config)
{
...
$this->belongsTo('Categories', [
'foreignKey' => 'category_id',
]);
...
}
...
}
Model/Table/CategoriesTable.php
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']);
}
Template/Articles/index.ctp
<?php foreach ($articles as $article): ?>
<tr>
<td>
<?= $article->category->name ?>
</td>
<td>
<?php endforeach; ?>
Here you can read more about Associations
Answered By - Jacek B Budzynski
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.