Relationship between tables (hasOne)

0

I have 2 tables one of images that belong to several different tables and in the other table the reference for id_image with the id of the table images.

In the image model I put:

$this->hasOne('Documentos')
     ->setName('Documentos')
     ->setDependent(true);

And in the model of the table I put:

$this->belongsTo('Imagenes')
     ->setForeignKey('id_imagen');    

In theory with this I relate the 2 tables but I do not know if I'm doing it right. Then another doubt that I have to show the name of the image, which is a field within the table of images called image would have to do something like $Documentos->imagen;

I use the latest version of CakePHP

    
asked by Isaac Palacio 28.06.2018 в 00:19
source

1 answer

1

I already found the solution, in case someone is interested:

Documents Table:

  

id | image_id | title | text

$this->hasOne('Imagenes')
     ->setBindingKey('id_imagen')
     ->setForeignKey('id');

Table Images:

  

id | table | image | type

$this->belongsTo('Documentos')
      ->setForeignKey('id_imagen')
      ->setJoinType('INNER');

Relationship:

  

Documentos.id_imagen = Imagenes.id

Document Controller:

public function Documento() {
    $documentos = TableRegistry::get('Documentos');
    $documentos = $documentos->find('all')
                             ->contain(['Imagenes']);
    $this->set('documentos', $documentos);
}

View:

<?= $documento->imagen->imagen; ?>
    
answered by 28.06.2018 в 13:36