I have part of structure database from my projects, in this case I want to create Tree from my categories that only have variant .
this is my database sturcture
there are categories table that have name and slug , and categories group table because I have more than one kind of category , also category_rel_variant for relationship with another object(in my case is variant)
my goal is Display categories that have variant and restructure that Tree . example
categories
| id | name | slug | partition |
| 1 | Animal | animal | null |
| 2 | monkey | monkey | null |
| 3 | Fruit | fruit | null |
| 4 | apple | apple | null |
| 5 | Banana | banana | null |
categories group
| id | cat_id | groups | description | parent | count |
| 1 | 1 | variant | animal variant | 0 | 0 |
| 2 | 3 | variant | fruit variant | 0 | 0 |
| 3 | 4 | variant | apple | 3 | 0 |
| 4 | 2 | variant | monkey | 1 | 0 |
| 5 | 5 | variant | banana | 3 | 0 |
categories_rel_variant
| id | cat_group_id | variant_id | sort |
| 1 | 5 | 1 | 1 |
| 2 | 1 | 2 | 2 |
variant
| id | name | {ect}
| 1 | green Banana is nice fruit
| 2 | there are monkey
when I try to query using this
SELECT gp.id AS 'id_cat_group', gp.cat_id AS 'fk_cat_id', gp.parent, gp.groups, cat.id AS 'cat_id', cat.name
FROM categories_groups gp
LEFT JOIN categories cat ON ( gp.cat_id = cat.id )
LEFT JOIN categories_rel_variant crv ON ( gp.id = crv.cat_group_id )
LEFT JOIN variant vr ON ( crv.variant_id = vr.id )
LEFT JOIN categories t4 ON ( gp.parent = t4.id )
WHERE gp.groups = 'variant_category'
AND crv.variant_id
IN ( 1, 2 )
LIMIT 0 , 30
that just give me current categories that have variant. my problem is I can't still get parent of that category.
from that result of quesry i want to re build tree to be like this
array(3) {
["id"]=>
string(1) "1"
["name"]=>
string(1) "Fruit"
["sub_category"]=>
array(2) {
["id"]=>
string(1) "5"
["name"]=>
string(23) "Banana",
['variant'] => {--- array variant(ect) ---}
}
}
and soon ..
Any suggestion How to make like I mean ?
To get the parent you have to perform another LEFT JOIN
on the categories
table:
...
LEFT JOIN categories t4 ON t0.parent = t4.id
The question was edited based on the above, but the following is also important.
Then adjust the SELECT
to include fields from this new table alias:
SELECT ..., t4.name AS subcat_name ...
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.