根据帖子ID检索标签

时间:2012-01-28 17:13:52

标签: php mysql sql database database-schema

我有三个表:postspost_tagstags。一个帖子可以有许多标签,一个标签可以属于许多帖子。由于这种多对多关系,我制作了一个post_tags表。它有两个字段:p_idt_id。它们分别是posts表和tags表的外键。现在,当我运行我的PHP方法来获取最新的帖子时,我想在一个查询中检索属于该帖子的标签。仅供参考,这是三个表:

帖子

| p_id | c_id | u_id |   title   |     body    |      published      |
----------------------------------------------------------------------
|  1   |  1   |   1  | first post| lorem ipsum | 2012-01-27 18:37:47 |

post_tags

| p_id | t_id |
---------------
|  1   |  3   |

标签

| t_id |     name    |     slug    |
------------------------------------
|  3   | programming | programming |

这是我现在用来获取没有标签的最新帖子的PHP代码:

public function getLatestPosts()
{
    $query = $this->db->query('SELECT title, clean_title, body, published FROM posts ORDER BY published DESC');
    $blogPosts = array();
    foreach ($query->result() as $row)
    {
        $blogPosts[] = array('title' => $row->title,
                             'clean_title' => $row->clean_title,
                             'body' => $row->body,
                             'published' => $row->published);
    }

    return $blogPosts;
}

如何调整查询以获取属于每个帖子的标签的名称和标记?

感谢您的帮助!

2 个答案:

答案 0 :(得分:1)

隐式联接:

SELECT title, clean_title, body, published, name, slug
FROM posts, posts_tags, tags
WHERE posts.p_id=posts_tags.p_id AND posts_tags.t_id=tags.t_id
ORDER BY published DESC

明确加入:

SELECT title, clean_title, body, published, name, slug
FROM posts
LEFT JOIN posts_tags ON posts.p_id=posts_tags.p_id
LEFT JOIN tags ON posts_tags.t_id=tags.t_id
ORDER BY published DESC

一次看到正确的规范化数据库架构令人耳目一新。

答案 1 :(得分:0)

你可能只想将它们构建成一个单独的数组,因为它是多对多的。

public function getLatestPosts()
{
    $query = $this->db->query('SELECT p_id, title, clean_title, body, published FROM posts ORDER BY published DESC');
    $blogPosts = array();
    foreach ($query->result() as $row)
    {
        $blogPosts[] = array('title' => $row->title,
                             'clean_title' => $row->clean_title,
                             'body' => $row->body,
                             'published' => $row->published,
                             'tags' => $this->getPostTags($row->p_id);
    }
    return $blogPosts;
}

public function getPostTags($pid)
{
    $query = $this->db->query('SELECT name, slug FROM tags INNER JOIN post_tags on tags.t_id = post_tags.t_id WHERE post_tags.p_id = ' . $pid);
    $postTags = array();
    foreach ($query->result() as $row)
    {
        $postTags[] = array('name' => $row->name,
                             'slug' => $row->slug);
    }
    return $postTags;
}