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

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

简单地说:标记HABTM文档

有没有办法找到所有没有关联文档标签

我从这个开始:

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

希望对你有帮助

关于php - CakePHP 查找没有 HABTM 关系记录的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14838210/

相关文章:

php - PHP session 劫持

php - php中如何删除子节点

php - 移动检测功能在我的网站上不起作用。

html - cakephp 如何将引导框架 css 样式包含到我的应用程序中?

javascript - MongoDB 查找具有多个 eq 的 expr

linux - 在/template 文件夹中查找所有 *.tpl 文件并递归地对它们进行 666 修改

javascript - 使用 JQuery 从数组中设置选择选项值和文本

css - 将按钮类添加到使用 html 帮助程序的表格单元格 <td>

authentication - Cakephp 授权 : $this->Auth->loginError message

python - beautifulsoup:找到第 n 个元素兄弟