Take a look at the Cakephp documentation for associations between Models (I put the 2.x version because I believe it is your case) and see the examples of uses of Models associations, as well as the use of the attribute Recursive to be able to bring all table items that are associated.
Example
Model:
Example n-n relationship
Model Table1:
<?php
App::uses('AppModel', 'Model');
class Tabela1 extends AppModel {
public $useTable = 'tabela_1';
public $hasAndBelongsToMany = array(
'Tabela2' =>
array(
'className' => 'Tabela2',
'joinTable' => 'tabela_relacionamento_1_2',
'foreignKey' => 'tabela_1_id',
'associationForeignKey' => 'tabela_2_id'
),
);
public function getAll(){
//Essa função irá retornar todos os itens da tabela_1 e também
//retornar os os itens que estão associados a cada um dos itens.
//Ex: $allItens = array(0 => array(
// 'Tabela1' => array('id' => 1, 'att1' => 'atributo1', att2 => 'atributo2'),
// 'Tabela2 => array('id' => 1, 'attr1' => 'attributo1', 'attr2' => 'attributo2)
//));
$allItens = $this->find('all',
'recursive' => 2
);
return $allItens;
}
}
Model Table2:
<?php
App::uses('AppModel', 'Model');
class Tabela2 extends AppModel {
public $useTable = 'tabela_2';
public $hasAndBelongsToMany = array(
'Tabela1' =>
array(
'className' => 'Tabela1',
'joinTable' => 'tabela_relacionamento_1_2',
'foreignKey' => 'tabela_2_id',
'associationForeignKey' => 'tabela_1_id'
),
);
}
Relationship 1-n
Model Table3:
<?php
App::uses('AppModel', 'Model');
class Tabela3 extends AppModel {
public $useTable = 'tabela_3';
public $hasMany = array(
'Tabela4' => array(
'className' => 'Tabela4',
'foreignKey' => 'tabela_3_id'
)
);
}
Model Table4:
<?php
App::uses('AppModel', 'Model');
class Tabela2 extends AppModel {
public $useTable = 'tabela_4';
public $belongsTo = array(
'Tabela3' => array(
'className' => 'Tabela3',
'foreignKey' => 'tabela_3_id'
)
);
public function getAll(){
//Essa função irá retornar todos os itens da *tabela_3* e também
//retornar os os itens que estão associados a cada um dos itens.
//Ex: $allItens = array(0 => array(
// 'Tabela4' => array('id' => 1, 'attribute1' => 'att1', attribute2 => 'att2'),
// 'Tabela3 => array('id' => 1, 'atributo1' => 'at1', 'atributo2' => 'at2)
//));
$allItens = $this->find('all',
'recursive' => 2
);
return $allItens;
}
}
You had already posted a reply. It is interesting to join both in one, in this case, join the previous one with this and delete it after.
– user28595
Managed to solve your problem @Diegofelipe?
– Julyano Felipe
Juliano, I didn’t ask the question. OP It’s @Danilomiguel
– user28595
True, confused by the fact that the first name is similar
– Julyano Felipe