1
我有兩個表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
方法返回與/所有Clazzes沒有相關的老師(我需要retrive只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`));
我不太瞭解cakephp 3.0來正確回答這個問題,但我認爲'clazzes_teachers.clazz_id = clazzes.id'上有一個'left join clazzes_teachers,其中where條件'where clazzes_teachers.clazz_id爲null'。我可以用cakephp 2.x'find('all',array(...))來寫這個;'如果你認爲那會有幫助。 – dragmosh