我想建立一个小型的电子商务网站,没什么特别的,没有添加到购物车,评级和类似的东西,但我确实有一个两难的境地。我需要有多个级别的类别。
因此,举例来说,如果我可能会有这样的事情:
Samsung
- Tv
- Smart Tv
- Samsuns Smart Tv s45
- Samsung Smart Tv k7x
- 3D Tv
- some product
- Laptops
- Intel Core 7
- Some product
- Inter Core 5
- Some product
LG
- same stuff
唯一的问题是类别的级别没有预定义,所以我不知道鬃毛水平会如何。
有人可以告诉我一些示例mysql数据库如何查找这种结构吗?
答案 0 :(得分:1)
对于多级别的类别
id | category_name | slug | parent_id
考虑这个设计
答案 1 :(得分:0)
我已经在Coldfusion中编写了此代码,您可以根据需要对其进行修改...
<cfquery name="Stuff" datasource="xyz">
SELECT CategoryId, CategoryName, ParentId
FROM Category
ORDER BY CategoryName
</cfquery>
<cfset RootItems=ArrayNew(1)>
<cfset Depth=ArrayNew(1)>
<cfset RowFromID=StructNew()>
<cfset ChildrenFromID=StructNew()>
<cfloop query="Stuff">
<cfset RowFromID[CategoryId]=CurrentRow>
<cfif NOT StructKeyExists(RowFromID, ParentId)>
<cfset ArrayAppend(RootItems, CategoryId)>
<cfset ArrayAppend(Depth, 0)>
</cfif>
<cfif NOT StructKeyExists(ChildrenFromID, ParentId)>
<cfset ChildrenFromID[ParentId]=ArrayNew(1)>
</cfif>
<cfset ArrayAppend(ChildrenFromID[ParentId], CategoryId)>
</cfloop>
<cfloop condition="ArrayLen(RootItems) GT 0">
<cfset ThisID=RootItems[1]>
<cfset ArrayDeleteAt(RootItems, 1)>
<cfset ThisDepth=Depth[1]>
<cfset ArrayDeleteAt(Depth, 1)>
<cfif StructKeyExists(RowFromID, ThisID)>
<cfset RowID=RowFromID[ThisID]>
<cfoutput>#RepeatString("--",ThisDepth)# #Stuff.CategoryName[RowID]#</cfoutput>
</cfif>
<cfif StructKeyExists(ChildrenFromID, ThisID)>
<cfset ChildrenIDs=ChildrenFromID[ThisID]>
<cfloop from="#ArrayLen(ChildrenIDs)#" to="1" step="-1" index="i">
<cfset ArrayPrepend(RootItems, ChildrenIDs[i])>
<cfset ArrayPrepend(Depth, ThisDepth + 1)>
</cfloop>
</cfif>
</cfloop>