[SalesForce] Access to related list in apex

I have a standard object Account and in this object Account I have four record types.
Two of the record types are "Partner" and "Partner Role".
In the "Partner" record type I have a related list "Partner Role".
In apex I'm using a SOQL query to take all Partner records and add them in a list.
I iterate over the list of Partners and for each Partner I need to get its "Partner Role" related list.

What I need to do in apex to access the related list in each Partner?

Here is a fragment of my code:

// return all accouts of type Partner
  List<Account> listOfPartners  = new List<Account>([SELECT id, Partner_Name__c, Partner_Roles__r.Company_Name__c FROM Account where RecordTypeId = '0120Z0000000yXz']);

  for (Account partner: listOfPartners) {    
      // How to get the related Partner_Roles__r list       
  }

In the above SOQL I get the following error message:

Didn't understand relationship 'Partner_Roles__r' in field path. If
you are attempting to use a custom relationship, be sure to append the
'__r' after the custom relationship name. Please reference your WSDL
or the describe call for the appropriate names.

Best Answer

Lets say the child relation ship name is Account_Partner_roles. Account is the parent of Partner Role here. You can get the Partner role records of a Account of particular record type using :

List<Account> acc = [Select id, name, RecordType.Name,(select id,Name from Account_Partner_roles__r) 
FROM Account
WHERE RecordType.Name IN ('Partner');

You can iterate over the Account list acc and get all the related list.

Related Topic