2011-05-11 47 views
0

如果你有如下表結構更新在MySQL標籤:刪除和使用PHP

item: id, content ect 
item_tags: item_id, tag_id 
tags: id, name 

如果一個項目可以有許多標籤。

我用下面的代碼來選擇屬於某一個項目標籤:

SELECT GROUP_CONCAT(DISTINCT tag.name 
ORDER BY tag.name DESC 
SEPARATOR ',') AS tags 
FROM item_tags 
JOIN tag ON item_tags.tag_id = tag.id 
WHERE item_id =1 

什麼策略[*]你會使用更新標記爲某一個項目?

雖然我做了以下內容:

  1. 從數據庫original_tags獲取標籤
  2. 標籤
  3. 獲取用戶更新爲changed_tags
  4. 刪除屬於該項目的所有標籤從數據庫
  5. 找到changed_tags和original_tags之間的區別,並將這些添加到數據庫中 。

看着每個標籤爲一個特定的項目,如果有多個已加入看到,一個被帶走,或者拼寫已經改變,似乎過於複雜,因此理刪除所有這些,爲此物品添加新標籤。

什麼認爲你?

*我不是在尋找實際的代碼 - 儘管

回答

0

我這樣做是在CF的設置,這將是很好的,所以我不能給你一個相關的代碼示例。但這裏是我的步驟:

1. Get all the tags from the DB for the item in question 
2. Put all the tags the user entered into an array 
3. Loop on all the tags from the DB 
4. Sub Loop on all the user supplied tags 
    4a. if there is a match then remove that tag from the user supplied array, 
    4b. if no match after going through the whole subloop delete the tag. 
5. Loop what is left in the user supplied array inserting them into the DB 

注意:如果我找到一個匹配我打出來的子循環,並移動到下一個父循環項目,以節省處理。

0

我認爲你根本不需要檢索原始標籤。您可以發出REPLACEINSERT ... ON DUPLICATE KEY UPDATE查詢來同步您收到的標籤和數據庫中的標籤。然後,您需要刪除不在新列表中的所有標籤(如果所有不在changed_tags列表中的標籤都應該刪除)或標記爲刪除的標籤(如果changed_tags中的標籤有刪除標誌)。