Federick Jons Federick Jons - 1 year ago 45
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): ?>
<td><?= $turno->has('cancha') ? $this->Html->link($turno->cancha->idCancha, ['controller' => 'Canchas', 'action' => 'view', $turno->cancha->idCancha]) : '' ?></td>

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): ?>
<td><?= $turno->has('cancha')->('complejo') ? $this->Html->link($turno->cancha->complejo->idComplejo, ['controller' => 'Canchas', 'action' => 'view', $turno->cancha->->complejo->idComplejo]) : '' ?></td>

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.


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 Source

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', 
     ]) : '' ?>