php - Mysql query which returns category tree -
I am working on category management. Where I have parents with each line categories can be n-level I can call the php function again, which will return to the tree tree array.
Now the problem is: admin In the panel, I want the category list page as listed below.
- / li>
- Products > Product 2 (edit) (delete)
- Products> Products 2> Products 2 1 (edit) (delete)
- Products> Product 2> Product 2 2 (edit (Delete)
- Contact us (edit) (delete)
I would like mysql query results in the same order as shown above. I'm not sure how I can achieve it.
SELECT * FROM tbl_categories ORDER BY ???
Please guide.
Any is not a single SQL query which will bring you the results the way From you are expected on the basis of this table structure.
There are two ways to solve this problem:
-
Use external application logic to create recursive calls (outside DB) Find children and make the tree in the application.
-
Use an algorithm for storage of trees In a relational database, the data is called an algorithm or just MPTT.
Let's say that we use the column lft
and rgt
in the left / transcendent right indexed, when you enter a new Enter the category, then you will need:
-
Get the basic category information from the ID:
SELECT lft, rgt FROM tbl_categories WHERE categoryId = 5
example For one case, assume that in the parent category,lft = 7
andrgt = 10
(in this case it has a baby already) -
Make room for a new entry - Change all records to 2 (1 for 1 and 1 for RGT):
UPDATE tbl_categories SET rgt = rgt + 2 WHERE rgt & gt; = 10 RGT DESC by order
UPDATE tbl_categories SET lft = lft + 2 WHERE lft & gt; <10> LFT DESC by ORDER
Note here ORDER
as descending lft
and Rgt
is considered unique, they are advised to have a UNIQUE
bound on them, and then the descending order in the update is required to prevent duplicate key errors.
-
Set
lft = & lt; Formerly original RGT & gt;
andrgt = & lt; Formerly original RGT + 1> Enter
and enter a new record ...INSERT SET categoryName = "new child" in TST category, parentCategoryId = 5, lft = 11, rgt = 12, .. .
If you search for MPTT PHP MySQL
, then you can find a more detailed example with code. There are some tutorials on this topic.
Comments
Post a Comment