繁体   English   中英

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

[英]CakePHP find items without HABTM relationship record

简单地说: Tags HABTM Documents

有没有办法找到没有Document关联的所有Tags

我从这开始:

$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'));

作为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'));

我希望它对你有所帮助

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM