0

I am utilizing the Account object to store both the Customer Account and its associated Billing accounts. How do I write a SOQL query to pull all billing accounts related to the customer account.

enter image description here

In the below image you can see the first account as Customer Account and all the below records are billing accounts related with the first Customer. The current relationship is using the Id field of the Customer Account to ParentId field of the Billing Accounts.

How do I write a SOQL to pull in related records if it is in the same object?

2

The following query would help:

SELECT Name, (SELECT Name FROM ChildAccounts) FROM Account

This will find all top-level accounts and their children. Note, however, if you have deeply nested accounts, you'd have to associate the nested children recursively. I have written a few examples, such as this one, this one, and probably others, too. It just requires a Map and a few for loops.

1
  • That helps, Thanks sfdcfox – sumchans Feb 5 at 16:55
0

You find the child relationship name the same way you would any other:

for (ChildRelationship relation : SObjectType.Account.getChildRelationships())
    system.debug(relation);

Comb through the debug logs and you will see getRelationshipName=ChildAccounts for the relevant ChildRelationship.

3
  • this would be on the same object, is it possible that we could pull the child records through SOQL. – sumchans Feb 5 at 1:42
  • Yes it still works like other joins. The syntax and mechanics are the same. – Adrian Larson Feb 5 at 1:46
  • Could you provide me with an example using SOQL for the above small data? – sumchans Feb 5 at 1:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.