CakePHP查找没有HABTM关系记录的项目

时间:2013-02-12 17:25:19

标签: php cakephp find cakephp-2.0 has-and-belongs-to-many

简单地说:Tags HABTM Documents

有没有办法找到没有关联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 个答案:

答案 0 :(得分: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'));

我希望它对你有所帮助