function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Frank U 2Frank U 2 

syntax to select child records, related records, and related records of child records

I'm having trouble composing the right code for the following data model. Arrows represent lookup fields (A has lookups for B & C, D has lookup for C).diagram of objects A, B, C, D. A looks up B & C, and D also looks up C.
For each myA record in an A_object list, I need to read the stringB field from its corresponding B_object, create the list of D_objects related to the same C_object, and read their stringD fields.

Statements I tried that don't work:

string myB = myA.B__r.stringB; // returns null

for (D_object myD : [select Id,stringD from D_object where C = :myA.C__r.Id]) // SOQL returns 0 records

C_object myC = myA.C // syntax error: illegal assignment from Id
C_object myC = myA.C.Id // syntax error: non foreign key can't be refererence
C_object myC = myA.C__r.Id // syntax error: illegal assignment from Id
C_object myC = myA.C__r // returns null

What is the correct syntax?
Alain CabonAlain Cabon
@Frank

The first problem is to have all your correct API names because we have doubts if the object names (label) are A, B, .. or A_object, B_object. with API names (A__c or A_object__c ).

There is one excellent technique;  setup > (quick find) API > Generate Enterprise WSDL (under Enterprise WSDL) > button: Generate (wait until you see a huge XML file that describes all your objects and relationship with their API names)

Then afer, copy/paste here the complexTypes for your custom objects: <complexType name="A__c"> ... ( or <complexType name="A_object__c"> )

These descriptions can be used in order to verify the correct syntax of SOQL queries (there are all the exact API names of the objects, fields and relationships).
  
Enterprise WSDL
A strongly typed WSDL for customers who want to build an integration with their salesforce.com organization only.
Generate Enterprise WSDL  (click here)