我有三個表格:posts
,post_tags
和tags
。一個帖子可以有很多標籤,一個標籤可以屬於很多帖子。由於這種多對多的關係,我做了一個post_tags
表。它有兩個字段:p_id
和t_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??
感謝您的幫助!
使用一個連接比另一個有什麼優勢? – 2012-01-28 17:24:23
這不會返回具有多個標籤的帖子的重複發佈數據的多個行嗎? – 2012-01-28 17:25:58
是的,它的確如此:/ – 2012-01-28 18:11:58