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.
- [1] stofDoctrineExtensionsBundle on GitHub;
- [2] stofDoctrineExtensinsBundnle documentation on Symfony.com;
- [3] Gedmo Tree documentation on GitHub;
- [4] Gedmo Tree > Tree Entity example;
- [5] Gedmo Tree > Basic Usage Example;
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.