Проще говоря: Tags HABTM Documents
CakePHP найти элементы без записи отношения HABTM
Есть ли способ, чтобы найти все 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
EDIT: Окончательное решение, метод в 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'));
Попробуйте идти через это: http://book.cakephp.org/2.0/en/models/retrieving -your-data.html # подзапросы – Dunhamzzz