+ Start a Discussion

account hierarchy id retrieval

Hi Forum Members,

I am trying to come up with a way to retrieve all Accounts within a hierarchy based on a supplied Id.  So, if the Id of the parent account is provided, all children records plus the parent record should be returned.  Similarly, if an Id of a child record is supplied, all parent, sibling, and children records should be returned.

User-added image

Any help in this regard is highly appreciated
Ravi Dutt SharmaRavi Dutt Sharma

If you want to go only 1 level up and 1 level down, then below SOQL will work for you.
SELECT Id, ParentId, (SELECT Id FROM ChildAccounts) FROM Account WHERE Id=:suppliedAccountId

If you want to go n-th level up and n-th level down, then you need to call this SOQL recursively until you come to a stage where there are no parent or child records returned from the query. I have done a similar implementation for role hierarchy, you can see the details below:

https://salesforcespace.blogspot.com/2020/01/building-org-role-hierarchy-component.html  (https://salesforcespace.blogspot.com/2020/01/building-org-role-hierarchy-component.html)
Hi Ravi, Thanks for your input. Appreciate your help in this regard.

I am able to retrieve the child from top to bottom. The issue what ia m facing is, if i get a id which is in the middle of the hierrarchy i wanted to retrieve all the ids above its hierarchy and below its hierarchy.

Let me know if it is clear