Skip to content

Instantly share code, notes, and snippets.

@Walletau
Last active March 29, 2017 16:28
Show Gist options
  • Save Walletau/dd022ad581e7829796829832437ff9f8 to your computer and use it in GitHub Desktop.
Save Walletau/dd022ad581e7829796829832437ff9f8 to your computer and use it in GitHub Desktop.
MagicParentsSnippet1
public static Set<Id> getTopAccountIds(Set<Id> accountsTargeted) {
Set<Id> topAccountIds = new Set<Id>();
Set<Id> recursivelyTargetedAccountIds = new Set<Id>();
for (Account targetedAccount : [
SELECT Id,
Name,
ChildrenUserGroupId__c,
ChildrenIncludedUserGroupId__c,
UserGroupId__c,
ParentUserGroupId__c,
ParentID,
Parent.ParentID,
Parent.Parent.ParentID,
Parent.Parent.Parent.ParentID
FROM Account
WHERE Id IN :accountsTargeted
]) {
if (targetedAccount.Parent.Parent.Parent.ParentID != null) {
recursivelyTargetedAccountIds.add(targetedAccount.Parent.Parent.Parent.ParentID);
} else if (targetedAccount.Parent.Parent.ParentId != null) {
topAccountIds.add(targetedAccount.Parent.Parent.ParentId);
} else if (targetedAccount.Parent.ParentId != null) {
topAccountIds.add(targetedAccount.Parent.ParentId);
} else if (targetedAccount.ParentId != null) {
topAccountIds.add(targetedAccount.ParentId);
} else {
topAccountIds.add(targetedAccount.Id);
}
}
if (!recursivelyTargetedAccountIds.isEmpty()) {
topAccountIds.addAll(getTopAccountIds(recursivelyTargetedAccountIds));
}
return topAccountIds;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment