Allows working with an "hierarchical" SObject relationships (Lookup or Master-detail that references the same SObject type. EG: Account.Parent
).
- Find the "root" (AKA highest parent)
- Find ALL children
- Works for any
SObject
git clone git@github.com:ChuckJonas/hierarchical-search.git
sfdx force:source:convert -d dist
sfdx force:mdapi:deploy -d dist -u your-user
RootSearch r = new RootSearch(Account.getSObjectType(), Account.ParentId);
Map<Id, Id> roots = r.search(new Set<Id>{ child.Id });
System.debug('The Root of this account is ' + roots.get(child.Id));
DescendantSearch r = new DescendantSearch(Account.getSObjectType(), Account.ParentId);
Map<Id, List<Id>> children = r.search(new Set<Id>{ parent.Id });
System.debug('This Account has ' + children.get(parent.Id).size() + ' children');
A common use case for this type of thing is to create an "Ultimate Parent Lookup" on an Account:
- Realtime (trigger) (TODO: Add Example)
- near-realtime (trigger + @future) (TODO: Add Example)
- Scheduled Batch Job
Depending on your requirements, you might use a combination of these approaches.
This code has been optimized to limit the number of SOQL queries and is capable of traversing "deep" trees. It for a depth of N
, it should return in CEIL(N/6)
SOQL queries.
MIT