Cakephp 是否可以将内部联接查询替换为habtm关系中的可包含查询?
我阅读了这一部分,但没有找到一个清晰的示例来用可包含查询替换habtm关系上的内部联接查询。例如: 型号Cakephp 是否可以将内部联接查询替换为habtm关系中的可包含查询?,cakephp,cakephp-2.0,has-and-belongs-to-many,containable,Cakephp,Cakephp 2.0,Has And Belongs To Many,Containable,我阅读了这一部分,但没有找到一个清晰的示例来用可包含查询替换habtm关系上的内部联接查询。例如: 型号 Student hasAndBelongsToMany Teacher Teacher hasAndBelongsToMany Student 查询 $joins = array( array( 'table' => 'teachers_students', 'type' => 'INNER', 'conditions'
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));
评论
- 在每个模型中设置
属性hasandbelongtomany
- 伪变量
对模型的引用:$this
class Student
是一个参数(有一个过滤器显示属于某个特定教师的学生)$teacherId
contain
,在不使用连接的情况下编写相同的查询。比如:
$contain = array(
'Teacher' => array(
'conditions' => array('???' => '???')
)
);
$data = $this->find('all', array('contain' => $contain));
如果我理解您的问题(试图让学生了解特定教师),您需要a)使用联接,或者B)切换查询方向,并从教师模型构建查询:
//Teacher Model
$this->find('all', array(
'conditions' => array('Teacher.id' => $teacherId),
'contain' => array(
'Student'
)
);
您不能根据包含模型的条件限制主模型的结果,因为使用“包含”实际上会创建单独的查询