2013-02-12 76 views
3

簡單地說:Tags HABTM DocumentsCakePHP的發現不HABTM關係記錄項目

有沒有辦法找到所有Tags沒有一個Document關聯?

我已經開始與此:

$freeTags = $this->Tag->find('all', array(
      'conditions' => array(
      ), 
      'contain' => array(
       'Document' 
      ), 
      'recursive' => -1 
     )) 

,但我不知道如何得到這樣的查詢:

SELECT * FROM tags WHERE id NOT IN (SELECT tag_id FROM documents_tags) 

我的CakePHP的版本是2.3

編輯: 最終溶劑,Tag模型中的方法

$db = $this->getDataSource(); 
    $subQuery = $db->buildStatement(
      array(
       'fields' => array('DocumentsTag.tag_id'), 
       'table' => $db->fullTableName($this->DocumentsTag), 
       'alias' => 'DocumentsTag', 
       'limit' => null, 
       'offset' => null, 
       'joins' => array(), 
       'conditions' => null, 
       'order' => null, 
       'group' => null 
      ), $this->DocumentsTag 
    ); 
    $subQuery = ' Tag.id NOT IN (' . $subQuery . ') '; 
    $subQueryExpression = $db->expression($subQuery); 

    $conditions[] = $subQueryExpression; 

    $freeTags = $this->find('all', compact('conditions')); 
+1

試圖通過這個打算:http://book.cakephp.org/2.0/en/models/retrieving -your-data.html#子查詢 – Dunhamzzz 2013-02-12 17:59:23

回答

1

由於CookBook :: Subqueries你可以做

$db = $this->User->getDataSource(); 
$subQuery = $db->buildStatement(
    array(
     'fields'  => array('"DocumentsTag"."tag_id"'), 
     'table'  => $db->fullTableName($this->DocumentsTag), 
     'alias'  => 'DocumentsTag', 
     'limit'  => null, 
     'offset'  => null, 
     'joins'  => array(), 
     'conditions' => null, 
     'order'  => null, 
     'group'  => null 
    ), 
    $this->DocumentsTag 
); 
$subQuery = ' "Tag"."id" NOT IN (' . $subQuery . ') '; 
$subQueryExpression = $db->expression($subQuery); 

$conditions[] = $subQueryExpression; 

$this->User->find('all', compact('conditions')); 

我希望它可能是有益的你

+0

謝謝,像一個魅力工作 – Elwhis 2013-02-13 09:26:10