【问题标题】:It is possible to replace an inner join query by a containable in a habtm relationship?可以用 habtm 关系中的可包含替换内部连接查询吗?
【发布时间】:2025-12-05 07:40:02
【问题描述】:

我阅读了Containable 部分,但没有找到一个明确的示例来用containable 查询替换关于habtm 关系的内部连接查询。示例:

型号

Student hasAndBelongsToMany Teacher
Teacher hasAndBelongsToMany Student

查询

$joins = array(
    array(
        'table' => 'teachers_students',
        'type' => 'INNER',
        'conditions' => array(
            'teachers_students.teacher_id' => $teacherId,
            'teachers_students.student_id = Student.id'
        )
    )
);

$data = $this->find('all', array('joins' => $joins));

评论

  • hasAndBelongsToMany 属性在每个模型中设置。
  • 伪变量$this参考模型:class Student
  • $teacherId 是一个参数(有一个过滤器可以显示属于某个特定教师的学生)。

我在寻找什么

为了能够在没有joins 的情况下编写相同的查询,请使用contain。类似的东西:

$contain = array(
    'Teacher' => array(
        'conditions' => array('???' => '???')
    )
);    

$data = $this->find('all', array('contain' => $contain));

【问题讨论】:

    标签: cakephp cakephp-2.0 has-and-belongs-to-many containable


    【解决方案1】:

    如果我理解您的问题(试图为特定教师获取学生),您需要 A) 使用联接,或 B) 切换查询的方向并从教师模型构建它:

    //Teacher Model
    $this->find('all', array(
        'conditions' => array('Teacher.id' => $teacherId),
        'contain' => array(
            'Student'
        )
    );
    

    您不能根据包含模型的条件限制主模型的结果,因为使用“包含”实际上会创建单独的查询。

    【讨论】:

      最近更新 更多