Mysql 如何使用CakePHP模型关联查找所有对象?

Mysql 如何使用CakePHP模型关联查找所有对象?,mysql,cakephp,model,foreign-keys,Mysql,Cakephp,Model,Foreign Keys,以下是我的数据库架构: 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

以下是我的数据库架构:

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');
}
然而,这将返回每个人物角色记录,而不仅仅是那些在Alumno表中有记录的人

你建议我如何解决这个问题?我想通过使用
$this->Alumno->Persona
我只会接触到Alumno表中的Persona


谢谢

您可以尝试动态创建
内部连接,如下所示:

$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);
您可以使用,只需在
校友
上查找

$this->set('personas', $this->Alumno->find('all'));
它应该检索“Alumno”及其关联的所有模型。您还可以选择要检索的模型。例如,此代码将检索所有“Alumno”及其对应的“Persona”

$this->set('personas', $this->Alumno->find('all',array('contain'=>array('Persona')));
A当然。。就像@Paulo Answeed一样,您可以手动进行连接,但是使用“containable”更干净。我只有在没有任何其他解决方案时才手动进行连接

希望这有帮助

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