I want to get this result: [Click Me][1] (get a link to go to the other associate table)
I’m following the official tutorial of cakephp to linking tables together but it’s not working.
My database is like this:
Table ciudades:
| id (int 4) PK | nombreCiudad (varchar 60)|
Table complejos:
| idComplejo (int 11) PK | nombre (varchar 25)| ciudad_id (int 4) FK |
The complete ciudad column in my complejo table is empty when I want to show the name of the another asociation model (ciudad nombreCiudad). I want to show the name, not the Id of Ciudad.
Here you can see the empty column:[Click Me 2][2]
When I want to show the result, in index.ctp “$complejo->has(‘ciudad’)” returns false:
<table cellpadding="0" cellspacing="0">
<thead>
<tr>
<th><?= $this->Paginator->sort('idComplejo') ?></th>
<th><?= $this->Paginator->sort('nombre') ?></th>
<th><?= $this->Paginator->sort('ciudad_id') ?></th>
<th class="actions"><?= __('Actions') ?></th>
</tr>
</thead>
<tbody>
<?php foreach ($complejos as $complejo): ?>
<tr>
<td><?= $this->Number->format($complejo->idComplejo) ?></td>
<td><?= h($complejo->nombre) ?></td>
<td><?= $complejo->has('ciudad') ? $this->Html->link($complejo->ciudad->nombreCiudad, ['controller' => 'Ciudades', 'action' => 'view', $complejo->ciudad->id]) : '' ?></td>
<td class="actions">
<?= $this->Html->link(__('View'), ['action' => 'view', $complejo->idComplejo]) ?>
<?= $this->Html->link(__('Edit'), ['action' => 'edit', $complejo->idComplejo]) ?>
<?= $this->Form->postLink(__('Delete'), ['action' => 'delete', $complejo->idComplejo], ['confirm' => __('Are you sure you want to delete # {0}?', $complejo->idComplejo)]) ?>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
Here you can see the relationship between ciudades and complejos
ComplejosTable.php
public function initialize(array $config)
{
parent::initialize($config);
$this->table('complejos');
$this->displayField('idComplejo');
$this->displayField('nombre');
$this->belongsTo('Ciudades', [
'foreignKey' => 'ciudad_id',
'joinType' => 'INNER'
]);
}
public function buildRules(RulesChecker $rules)
{
$rules->add($rules->existsIn(['ciudad_id'], 'Ciudades'));
return $rules;
}
And here is CiudadesTable.php
...
public function initialize(array $config)
{
parent::initialize($config);
$this->table('ciudades');
$this->displayField('nombreCiudad');
$this->primaryKey('id');
$this->addBehavior('Timestamp');
$this->hasMany('Complejos', [
'foreignKey' => 'ciudad_id'
]);
}
Finally, in my ComplejosController I have:
public function index()
{
$this->paginate = [
'contain' => ['Ciudades']
];
$this->set('complejos', $this->paginate());
$this->set('_serialize', ['complejos']);
}
What can I do to resolve my problem? Thanks for helping.
[1]: http://imgur.com/Adh42B0
[2]: http://imgur.com/xJCixrG