2013-02-12 2 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

EDIT: Окончательное решение, метод в 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

ответ

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

Смежные вопросы