1

我正在用 CakePHP 写博客,所以我的数据库中有两个与 HABTM 相关的表:帖子和标签。因为它们与 HABTM 相关,所以我也有一个 posttags 表来跟踪关系。

我想在我的 tags_controller 中有一个方法来删除所有未使用的标签。

如何找到与任何帖子无关的所有标签?

4

2 回答 2

2

您可以使用以下语句删除所有未使用的标签:

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

(并且要查找与任何帖子无关的所有标签,只需将“delete”替换为“select *”)

于 2009-09-20T15:49:47.417 回答
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',
        ),
    ),
),

));

于 2009-09-22T04:25:23.007 回答