【问题标题】:How to get all tags that do NOT have posts associated in CakePHP如何获取在 CakePHP 中没有关联帖子的所有标签
【发布时间】:2009-09-20 12:44:32
【问题描述】:

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

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

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

【问题讨论】:

  • 您好,anderstornvig 先生,您能否指导我如何设法添加与帖子相关的多个标签。我正在尝试实现相同的功能,但无法正确完成。谢谢。

标签: cakephp find has-and-belongs-to-many


【解决方案1】:

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

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

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

【讨论】:

  • 谢谢,它有效。不过,我仍然愿意接受更“cakephp 风格”的答案。
【解决方案2】:
$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',
        ),
    ),
),

));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-31
    • 1970-01-01
    相关资源
    最近更新 更多