1

Introduction

I am using Symfony v3.1.6, Doctrine v2.5.4 and StofDoctrineExtensionsBundle [1] in order to manage Tree structure.

To setup Tree structure I used documentation on Symfony.com [2] followed by documentation on GitHub [3]. Then I proceeded with tree setup - used tree entity from example [4] and used code in [5] to create a tree.

Code

Function in CategoryRepository

public function getParentId($child_node_id)
{
    // get parent_id of a tree element
    $em = $this->getEntityManager();
    $query = $em->createQueryBuilder()
        ->select('c')
        ->from('AppBundle:Category', 'c')
        ->where('c.id = :nodeId')
        ->setParameter('nodeId', $child_node_id)
        ->setMaxResults(1)
        ->getQuery();

    $parent = $query->getResult();
    $parent_null = $parent[0]->getParent();

    // if parent element is null - efectively element is root of the tree
    if ($parent_null === null)
    {
        $parent_id = $parent[0]->getId();
    }
    // if parent element is not root of the tree
    else
    {
        $parent_id = $parent[0]->getParent()->getId();
    }

    return $parent_id;
}

When I use $parent = $query->getResult() I get following output:

array:1 [?
  0 => Category {#581 ?
    -id: 3
    -title: "Vegetables"
    -is_file: false
    -lft: 4
    -lvl: 1
    -rgt: 11
    -root: Category {#518 ?}
    -parent: Category {#518 ?
      -id: 1
      -title: "Food"
      -is_file: false
      -lft: 1
      -lvl: 0
      -rgt: 12
      -root: Category {#518}
      -parent: null
      -children: 

but when I use $parent = $query->getArrayResult() I get:

array:1 [?
  0 => array:6 [?
    "id" => 2
    "title" => "Fruits"
    "is_file" => false
    "lft" => 2
    "lvl" => 1
    "rgt" => 3
  ]
]

Note that there is no parent_id in the getArrayResult output...

Question

So the question is - how can one get tree node parent_id in the query result with getArrayResult ?

Conclusion

Please advise.

Thank you for your time and knowledge.

4

1 回答 1

3

事实证明,在使用时必须提示获取所有相关值getArrayResult

Vanilla answer [1] 对我不起作用,所以我做了一些修改(查询的完整路径)。

$query->setHint(\Doctrine\ORM\Query::HINT_INCLUDE_META_COLUMNS, true);

请注意,提示正在进行,$query并且位于查询和获取结果之间。

链接:

  1. 在这里找到初始信息
  2. 关于提示的文档
于 2016-11-01T22:15:04.180 回答