2015-02-08 81 views
1

我想實現文章帖子的標籤功能,因此用戶可以在發佈文章時添加多個標籤。從INSERT IGNORE語句獲取多個插入ID

我有一個tags表,一個articles表和一個article_tags表。

標籤:

id | tag (Unique) 

文章:

id | title | content 

article_tags:

id | article_id | tag_id 

所以,(1)當一個新的文章是插入,我需要插入articles表格並獲取插入標識爲article_id

(2)然後,我使用單個INSERT IGNORE語句將多個標記插入到tags表中。在這些標籤中,有些可能存在並將被忽略。

(3)現在我要將文章和標籤的關係插入article_tags。但是,如何將步驟(2)中的ID作爲最後一個表中的tag_id

或者我只是不能(而不是使用一個一個的插入解決方案)?

回答

0

型號:

public function insert_articles($data) 
    { 
     $this->db->insert('articles', $data); 
     return $this->db->insert_id(); 
    } 

    public function insert_tags($data) 
    { 
    $insert_query = $this->db->insert_string('tags', $data); 
    $insert_query = str_replace('INSERT INTO','INSERT IGNORE INTO',$insert_query); 
    $this->db->query($insert_query); 

    return $this->db->insert_id(); 
    } 

    public function insert_article_tags($data) 
    { 
    return $this->db->insert_batch('articles_tags', $data); 
    } 

控制器:

public function myfunction() 
    { 
    $id_article = $this->my_model->insert_articles($data); 
    $article_tags = array(); 
    foreach($mytags as $t) 
    { 
     $id_tag = $this->my_model->insert_articles($data); 
     array_push($article_tags, array("id_article" => $id_article, "id_tag" => $id_tag)); 
     //Supposed two fields table : id_article | id_tag 
    } 

    $this->my_model->insert_article_tags($data); 
    } 
+0

你可能誤解了我的問題。 – mrmoment 2015-02-08 10:59:04

+0

@mrmoment,絕對,對不起。看我的編輯。 – AdrienXL 2015-02-08 11:10:23

1

@ AdrienXL的答案是一個接一個的解決方案。

我發現我可以先批量插入標籤INSERT IGNORE

而當我插入article_tags的關係時,可以使用「批量選擇」查詢來獲取ID。所以我不一定需要在tags表中手動提取和存儲標籤的ID。

僞SQLS想:

INSERT IGNORE tags (tag) VALUES [the tag array] 

而且

INSERT INTO article_tags (tag_id, article_id) 
    SELECT id, [some_article_id] FROM tags WHERE tag IN [the tag array]