2016-01-27 156 views
1

我有兩個表ClazzesTeachers,都加入了第三個表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只ClazzesTeachers

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

我不太瞭解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

回答

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()

相關問題