Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/283.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在PHP中从子类别中获取父节点?_Php_Mysql_Tree - Fatal编程技术网

如何在PHP中从子类别中获取父节点?

如何在PHP中从子类别中获取父节点?,php,mysql,tree,Php,Mysql,Tree,我从我的项目中得到了部分结构数据库,在这种情况下,我想从只有变量的类别中创建树 这是我的数据库结构 有包含名称和slug的categories表,还有categories group表,因为我有不止一种类别,还有category_rel_variant,用于与另一个对象的关系(在我的例子中是variant) 我的目标是显示具有变体的类别,并重新构造该树。 范例 类别 | id | name | slug | partition | | 1 | Animal | animal | null

我从我的项目中得到了部分结构数据库,在这种情况下,我想从只有变量的类别中创建树

这是我的数据库结构

有包含名称和slug的categories表,还有categories group表,因为我有不止一种类别,还有category_rel_variant,用于与另一个对象的关系(在我的例子中是variant)

我的目标是显示具有变体的类别,并重新构造该树。 范例

类别

| id | name | slug | partition | 
| 1  | Animal | animal | null |
| 2  | monkey   | monkey | null |
| 3  | Fruit   | fruit | null |
| 4  | apple    | apple  | null |  
| 5  | Banana   | banana | null |
类别组

| 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 |
类别\u相对\u变量

| id | cat_group_id | variant_id | sort |
| 1  | 5            | 1 | 1 |
| 2  | 1            | 2 | 2 | 
变体

| id | name | {ect}
| 1  | green Banana is nice fruit
| 2  | there are monkey
当我尝试使用此

    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
这只是给了我目前的类别,有变化。我的问题是,我仍然无法获得该类别的父级

根据这个问题的结果,我想把树重建成这样

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) ---}

        }
    } 
很快


有什么建议吗?要获得家长,您必须在
类别
表上执行另一个
左连接

...
LEFT JOIN categories t4 ON t0.parent = t4.id
该问题是根据上述内容编辑的,但以下内容也很重要

然后调整
选择
以包括此新表别名中的字段:

SELECT ..., t4.name AS subcat_name ...

另外,我强烈建议您不要使用那些糟糕的别名,也不要使用表别名,除非您查询了两次。我已经更新了我的问题,我看到您已经用我的部分答案编辑了您的问题;但是,您忘了选择相应的字段,即
选择t4.name作为子类别名称…
树中是否有多代(父、子、孙等)?也就是说,以水果为母体的香蕉也会有孩子吗(香蕉的类型)?如果是,是否对受支持的代数(父母、子女、孙子等)有限制?此外,如果是这样的话,在获取3代的情况下,预期的结果会是什么样子?或者-这是什么变体应该反映(孙辈)?有人能给我样本吗?