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.

Rikijs
  • 728
  • 1
  • 12
  • 48

1 Answers1

3

Turns out one has to hint to get all the related values when using getArrayResult.

Vanilla answer [1] did not work for me, so I made little modification (full path to Query).

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

Note, that hinting is going on on the $query and is placed between query and getting the result.

Links:

  1. Found initial info here
  2. Documentation on hints
Community
  • 1
  • 1
Rikijs
  • 728
  • 1
  • 12
  • 48