2010-08-14 54 views
2

我想在這裏創建一個麪包屑,我在做這件事時遇到了一些麻煩。問題在於我必須保存類別名稱(使用兩種語言),slug和id。嘗試使用PHP和MySQL獲取節點的路徑

我的類別表看起來像這樣:

CREATE TABLE `categories` (
`category_id` smallint(5) unsigned NOT NULL AUTO_INCREMENT, 
`category_name` varchar(256) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL, 
`category_slug` varchar(256) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL, 
`category_parent` smallint(5) unsigned NOT NULL DEFAULT '0', 
`category_description_ro` text CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL, 
`category_description_en` text CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL, 
PRIMARY KEY (`category_id`) 
) ENGINE=MyISAM AUTO_INCREMENT=8 DEFAULT CHARSET=latin1 

貝婁是表中的數據的一個例子:

category id | category name | category_parent 

1   Categoria 1   0   
2   Categoria 2   0   
3   Categoria 3   0   
4   Categoria 1.1   1   
5   Categoria 1.2   1   
6   Categoria 1.3   1   
7   Categoria 1.1.2  4 

我不得不提,我不能做任何改變MySQL表。

我想什麼來完成是建立就像一個麪包屑:

首頁> Categoria 1> Categoria 1.1> Categoria 1.1.2

任何人都可以提供小塊代碼如何做到這一點? 我已經嘗試過從「here」到「節點的路徑」代碼,但正如我所說的,我必須在該數組中包含category_name,category_slug,category_description_ro和category_description_en。 在此先感謝你們。

回答

1

在僞代碼:

$currentID = 7; 
do{ 
    $category = getCategoryByID($currentID); 
    $currentID = $category['category_parent']; 

    $crumb .= $category['category_name']; 
}while($category['category_parent']); 

這隻會循環備份類別樹,建築碎塊,直到沒有更多的家長。

2

您正在使用adjacency list model組織您的分層數據。這種遞歸操作很困難的事實實際上是這種模型的一個主要缺點。

某些DBMS(如SQL Server 2005,Postgres 8.4和Oracle 11g)支持使用common table expressionsWITH關鍵字的遞歸查詢。此功能允許輕鬆編寫這樣的查詢,但不幸的是,MySQL不支持遞歸查詢。

您提到您無法對錶格進行任何更改,但可以添加額外的表格嗎?如果是的話,你可能會感興趣的檢查出下面的文章描述了另一種模式(在nested set model),這使得遞歸操作容易(可能):

此外,我還建議通過@Bill Karwin檢查出下面的介紹,對堆棧溢出的定期撰稿人:

演示文稿中描述的閉包表模型是嵌套集的非常有效的替代方案。他在他的SQL Antipatterns書(excerpt from the chapter on this topic)中進一步描述了這個模型。

否則,您可能想要在您的應用程序中執行遞歸部分,在php中,作爲@geon suggested的其他答案。

+0

我喜歡Bill Karwin的演講,謝謝。 – Psyche 2010-08-14 17:19:09