简单地说:标记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/