Last active
March 29, 2017 16:28
-
-
Save Walletau/dd022ad581e7829796829832437ff9f8 to your computer and use it in GitHub Desktop.
MagicParentsSnippet1
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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