2012-09-15 19 views

回答

3
  1. 你在這裏有什麼是多對多的關係。存儲關係的標準方法是使用類別和帖子的連接表。該表只會包含類別ID和帖子ID。

  2. 帖子表中沒有關於類別本身的信息。

0

大家(包括我自己)似乎正在使用的解決方案是@rwilliams描述的。當查詢限於單個標籤時,這些工作很好。對於查詢2個標籤(標記爲個人並標記爲旅行),您需要使用連接。當查詢變得更加複雜時,這開始中斷。 MongoDB將是我認爲的更好的解決方案。

0

對於多對多的關係,你可以設計你的表作爲

caegory table 
    categoryId categorydescription 

post table  
    postid  postText 

a third table to link them  
    categoryId postId 
0
blog_posts 
========== 
id | 23 
title | My title 

categories 
========== 
id | 1 
name | yogurt 
// another row 
id | 2 
name | motor cycles 

category_blog_post 
================== 
23 | 2 
23 | 1 

顯示的條目,其中博客文章我的標題被標記爲約酸奶和摩托車

1
  1. 這是什麼是正確的MySQL表模式?

    一種方法是創建一個關係表:

    CREATE TABLE cms.Posts (
        PostID  SERIAL, 
        PostContent TEXT, 
        PRIMARY KEY (PostID) 
    ) Engine=InnoDB; 
    
    CREATE TABLE cms.Categories (
        CategoryID SERIAL, 
        CategoryName VARCHAR(20), 
        PRIMARY KEY (CategoryID) 
    ) Engine=InnoDB; 
    
    CREATE TABLE cms.PostCategories (
        PostID BIGINT UNSIGNED NOT NULL, 
        CategoryID BIGINT UNSIGNED NOT NULL, 
        PRIMARY KEY (PostID, CategoryID), 
        FOREIGN KEY (PostID)  REFERENCES cms.Posts  (PostID), 
        FOREIGN KEY (CategoryID) REFERENCES cms.Categories (CategoryID) 
    ) Engine=InnoDB; 
    
  2. 你如何存儲在博客文章表中的多個選擇的類別?

    你不這樣做,你把它們存儲在PostCategories表:

    $dbh = new PDO('mysql:charset=utf8', $username, $password); 
    $dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); 
    
    $dbh->prepare('INSERT INTO cms.Posts (PostContent) VALUES (?)') 
        ->execute([$_POST['content']]); 
    
    $qry = $dbh->prepare(' 
        INSERT INTO cms.PostCategories (PostID, CategoryID) VALUES (?, ?) 
    '); 
    
    $qry->bindValue(1, $dbh->lastInsertId()); 
    $qry->bindParam(2, $category); 
    foreach ($_POST['categories'] as $category) $qry->execute(); 
    
+0

能否請您解釋一下在第二和第三的最後幾行。 – Rohitink

相關問題