简单地说: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'));
答案 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'));
我希望它对你有所帮助