【问题标题】:How to find all objects using CakePHP model associations?如何使用 CakePHP 模型关联查找所有对象?
【发布时间】:2012-10-04 15:14:46
【问题描述】:

这是我的数据库架构:

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');
}

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

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

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

但是,这将返回每条 Persona 记录,而不仅仅是在 Alumno 表中有记录的那些记录。

你建议我如何解决这个问题?我认为通过使用$this-&gt;Alumno-&gt;Persona,我只会接触到 Alumno 表中的 Persona。

谢谢!

【问题讨论】:

    标签: mysql cakephp model foreign-keys


    【解决方案1】:

    您可以使用containable behaviour 并在Alumno 上进行查找??

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

    它应该检索“Alumno”以及与之关联的所有模型。您还可以选择要检索的模型。例如,此代码将检索所有“Alumno”及其对应的“Persona”

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

    当然......就像@Paulo 回答的那样,您可以手动进行连接,但使用“可包含”更清洁。我只有在没有其他解决方案时才手动加入。

    希望对你有帮助,

    【讨论】:

      【解决方案2】:

      您可以尝试即时生成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);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-08-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多