Federick Jons Federick Jons - 5 months ago 13
MySQL Question

Display data through foreign key in cakephp

in Index.php from my View of Turno I have this:

<?php foreach ($turnos as $turno): ?>
<tr>
<td><?= $turno->has('cancha') ? $this->Html->link($turno->cancha->idCancha, ['controller' => 'Canchas', 'action' => 'view', $turno->cancha->idCancha]) : '' ?></td>
</tr>


This code works right. BUT I want to show the id of "Complejo", and "Complejo" is the foreign key of "Cancha". So... I want to navigate twice.. Something like this:

<?php foreach ($turnos as $turno): ?>
<tr>
<td><?= $turno->has('cancha')->('complejo') ? $this->Html->link($turno->cancha->complejo->idComplejo, ['controller' => 'Canchas', 'action' => 'view', $turno->cancha->->complejo->idComplejo]) : '' ?></td>
</tr>


But is not working. How can I navigate twice? The connection between "Turno" and "Cancha" is Ok and the connection between "Cancha" and "Complejo" is ok.

Thanks!

EDIT
The relationship between tables are:

In ComplejosTable:

$this->hasMany('Canchas', [
'foreignKey' => 'complejoFK'
]);


In CanchasTable:

$this->belongsTo('Complejos', [
'foreignKey' => 'complejoFK',
'joinType' => 'INNER'
]);

$this->hasMany('Turnos', [
'foreignKey' => 'canchaFK'
]);


In TurnosTable:

$this->belongsTo('Canchas', [
'foreignKey' => 'canchaFK',
'joinType' => 'INNER'
]);

Answer

You have to add Complejos to the contained Tables

'contain' => ['Canchas', 'Canchas.Complejos', 'Usuarios']

so you can do

 <?= $turno->has('cancha') && $turno->cancha->has('complejo') ?
     $this->Html->link($turno->cancha->complejo->nombre,  [
        'controller' => 'Complejos',
        'action' => 'view', 
        $turno->cancha->id_complejo
     ]) : '' ?>