+ Start a Discussion
Jake GmerekJake Gmerek 

Is there a better way

Hello,

 

I have three custom objects object1, object2, and object3.

 

Object2 is looks up a field in object1 and is the master of object3

 

In an apex class I have a query like List<object1> testList = new List<object1>( [select name, Object2_relationship_to_Object1__r.id from object 1])

 

What I need to do is take the id that is returned from object2 and get all the members of object3 that are related to it (select name from object 3 where id =: testList.Object2_relationship_to_Object1.id), but the only way that I can think to do it is interate through testList and call another query, which I know is bad because of governor limits.  Is there a better way to do this?

 

Thanks

Best Answer chosen by Admin (Salesforce Developers) 
sfdcfoxsfdcfox

 

SELECT Id,Name,
(SELECT Id,Name FROM Object1Relationship__r),
(SELECT Id,Name FROM Object3Relationship__r)
FROM Object2__c WHERE Id IN (SELECT Object1_Lookup_To_Object2__c FROM Object1__c)

 You use two sub-queries to find the list of Object1 and Object3 associated with Object 2. If you need to filter based on Object1, you can use a sub-query in the filter clause (shown in the example above).