我有两个表Clazzes
和Teachers
,两个表都由第三个表clazzes_teachears
连接。如何检索没有Clazzes
关联的Teachers
?现在我只能返回所有Clazzes
个元素,无论是否有教师关联。
ClazzesTable.php初始化
public function initialize(array $config)
{
parent::initialize($config);
$this->table('clazzes');
$this->displayField('name');
$this->primaryKey('id');
$this->belongsToMany('Teachers', [
'foreignKey' => 'clazz_id',
'targetForeignKey' => 'teacher_id',
'joinTable' => 'clazzes_teachers'
]);
}
TeachersTable.php初始化
public function initialize(array $config)
{
parent::initialize($config);
$this->table('teachers');
$this->displayField('id');
$this->primaryKey('id');
$this->belongsToMany('Clazzes', [
'foreignKey' => 'teacher_id',
'targetForeignKey' => 'clazze_id',
'joinTable' => 'clazzes_teachers'
]);
}
注意:不存在ClazzesTeachersTable.php
返回包含/不包含教师的所有Clazz的方法(我只需要Clazzes
只需Teachers
public function getAllClazzesRecursive(){
return $this
->find('all')
->contain([
'Teachers' => function($q) {
return $q->select(['id', 'registry', 'url_lattes', 'entry_date', 'formation', 'workload', 'about', 'rg', 'cpf', 'birth_date', 'situation']);
}
])->hydrate(false)->toArray();
}
老师sql:
CREATE TABLE IF NOT EXISTS `teachers` (
`id` INT NOT NULL AUTO_INCREMENT,
`registry` VARCHAR(45) NOT NULL,
PRIMARY KEY (`id`));
Clazzes sql:
CREATE TABLE IF NOT EXISTS `clazzes` (
`id` INT NOT NULL AUTO_INCREMENT,
`name` VARCHAR(45) NOT NULL,
PRIMARY KEY (`id`));
clazzes_teachers sql:
CREATE TABLE IF NOT EXISTS `clazzes_teachers` (
`clazz_id` INT NOT NULL,
`teacher_id` INT NOT NULL,
PRIMARY KEY (`clazz_id`, `teacher_id`));
答案 0 :(得分:3)
使用联接查询构建器,查看更多http://book.cakephp.org/3.0/en/orm/query-builder.html#adding-joins
public function getAllClazzesRecursive(){
return $this
->find('all')
->join([
'table' => 'clazzes_teachers',
'alias' => 'ct',
'type' => 'LEFT',
'conditions' => 'ct.clazz_id= clazzes.id',
])
->where('ct.id IS NULL')
->hydrate(false)->toArray();
}
您也可以直接使用leftJoin()
。