2012-10-04 37 views
0

这里是我的数据库模式:如何使用CakePHP模型关联查找所有对象?

create table Personas 
(
    id int primary key AUTO_INCREMENT, 
    Nombre varchar(255), 
    Apellidos varchar(255), 
    FechaDeNacimiento date, 
    Sexo Bool, 
    CarnetDeIdentidad varchar(255) 
); 

create table Tutors 
(
    id int primary key AUTO_INCREMENT, 
    persona_id int, 
    FOREIGN KEY (persona_id) REFERENCES Personas(id) 
); 

create table Alumnos 
(
    id int primary key AUTO_INCREMENT, 
    persona_id int, 
    FOREIGN KEY (persona_id) REFERENCES Personas(id) 
); 

create table CoordinadorDeProgramas 
(
    id int primary key AUTO_INCREMENT, 
    persona_id int, 
    FOREIGN KEY (persona_id) REFERENCES Personas(id) 
); 

这里是我的模型声明:

<?php 
class Alumno extends AppModel { 
    public $belongsTo = 'Persona'; 
} 

<?php 
class Coordinadordeprograma extends AppModel { 
    public $belongsTo = 'Persona'; 
} 

<?php 
class Tutor extends AppModel { 
    public $belongsTo = 'Persona'; 
} 

<?php 
class Persona extends AppModel { 
    public $hasOne = array('Alumno', 'Tutor', 'Coordinadordeprograma'); 
} 

在我的控制器我只是想,如果他们有Alumnos外键关系(获取所有的Persona记录例)。

这里是我的代码,我希望它说明了什么我想要做的事:

public function filter($type = null) { 
    if ($type == "alumno") { // www.app.com/personas/filter/alumno 
     $this->set('personas', $this->Alumno->Persona->find('all')); 
    } 
} 

但是这是回访每一个假面记录,而不是只具有在Alumno表中的记录的人。

你如何建议我解决这个问题?我认为通过使用$this->Alumno->Persona我只能到达Alumno表中的女神人物。

谢谢!

回答

1

您可以使用containable behaviour,只是做一个找到Alumno

$this->set('personas', $this->Alumno->find('all')); 

它应该检索与所有模型关联的'Alumno'。你也可以选择你想要检索的女巫模型。例如,该代码将检索所有的“Alumno”与其相应课程的“假面”

$this->set('personas', $this->Alumno->find('all',array('contain'=>array('Persona'))); 

的..像@Paulo回答,您可以手动进行连接,但使用“中可容纳”更干净。当我没有任何其他解决方案时,我只手动进行连接。

希望这会有所帮助,

1

你可以尝试随时进行INNER JOIN,像这样:

$personas = $this->Alumno->Persona->find('all', array(
    'joins' => array(
     array(
      'table' => 'Alumnos', 
      'alias' => 'Alumno', 
      'type' => 'INNER', 
      'conditions' => 'Persona.id = Alumno.persona_id' 
     ) 
    ) 
)); 

$this->set('personas', $personas);