2009-09-20 44 views
1

我在CakePHP中做博客,所以我在我的數據庫中有兩個與HABTM相關的表:帖子和標籤。因爲他們是HABTM相關的我也有關係的poststags表保持跟蹤。如何獲取所有CakePHP中沒有帖子關聯的標籤

我想在我的tags_controller中有一個方法,它將刪除所有未使用的標籤。

如何找到不與任何職位相關聯的所有標籤?

+0

您好Mr. anderstornvig, 您能否引導我如何設法添加與帖子相關的多個標籤。我正在嘗試實現相同的功能,但無法正確執行。 謝謝。 – 2009-10-20 07:08:32

回答

2

您可以使用下面的語句刪除所有未使用的標籤:

$this->query('delete from tags where not exists (select * from posts_tags where posts_tags.tag_id = tags.id)');

(並找到不與任何職位相關聯的所有標籤只需更換「刪除」和「選擇*」)

+0

謝謝你,它的工作原理。我還是願意接受更多的「CakePHP的風格」的回答,雖然。 – anderstornvig 2009-09-20 19:28:33

+0

偉大的查詢,謝謝! – kicaj 2013-08-20 15:24:14

0
$this->Tag->find('all', array(
'conditions' => array(
    'PostsTag.id IS NULL' 
), 
'joins' => array(
    array(
     'table' => 'poststags', 
     'alias' => 'PostsTag', 
     'type' => 'LEFT', 
     'conditions' => array(
      'PostsTag.tag_id' => 'Tag.id', 
     ), 
    ), 
), 

));

相關問題