9

Is it possible to access the children of a parents record using SOQL. For example, from Opportunities I can access the Account details (the parent):

SELECT Id, Name, Account.Id, Account.Name FROM Opportunity

and from Accounts I can access the Contacts (the children):

SELECT Id, Name, (SELECT Id FROM Contacts) FROM Account

but can I access the Contacts from the Opportunity? I'd like to use something like this:

SELECT Id, Name, Account.Id, Account.Name, (SELECT Id FROM Account.Contacts) FROM Opportunity

I know I could use two queries to get the information, but I'd like to be able to do it from a single query.

0

2 Answers 2

9

Not directly. What you can do is query the parent. Something like:

List<Account> accounts = [
    SELECT Id, Name, (SELECT Id FROM Contacts), (SELECT Id, Name FROM Opportunities)
    FROM Account
    WHERE Id IN (SELECT AccountId FROM Opportunity)
];

That way you'll get information from the accounts, but use the opportunity as a filter. (on the example: only accounts that have opportunities will be retrieved).

1
  • 1
    Oh, sorry @bigassforce . I just edited the example. Commented Jun 2, 2016 at 11:33
1

Are you trying to get both the contacts and opportunities together in one query?

Account a = [
    SELECT Id, 
           Name,
           (SELECT Id, FROM Contacts), 
           (SELECT Id FROM Opportunities) 
    FROM Account
    WHERE AccountId = '<AccountId>'
];
System.debug(a.Name);
System.debug(a.Contacts);
System.debug(a.Opportunities);

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .