2012-01-28 109 views
1

我有三個表格:postspost_tagstags。一個帖子可以有很多標籤,一個標籤可以屬於很多帖子。由於這種多對多的關係,我做了一個post_tags表。它有兩個字段:p_idt_id。它們分別是posts表和tags表的外鍵。現在,當我運行PHP方法獲取最新帖子時,我還想在一個查詢中檢索屬於該帖子的標籤。僅供參考,下面是這三個表:基於帖子ID檢索標籤

帖子

| 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; 
} 

我該如何調整我的查詢以獲取屬於每個帖子的標籤的名稱和slu??

感謝您的幫助!

回答

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 

讓人耳目一新,看到一個正確的,規範化的數據庫架構一次。

+0

使用一個連接比另一個有什麼優勢? – 2012-01-28 17:24:23

+0

這不會返回具有多個標籤的帖子的重複發佈數據的多個行嗎? – 2012-01-28 17:25:58

+0

是的,它的確如此:/ – 2012-01-28 18:11:58

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; 
}