For simplicity I will rename your objects to:
X
=> Detail
Y
=> Parent
Z
=> Child
The most reasonable interpretation of your OP I can infer is:
If I have a collection of Child
records, how can I find Detail
records for the same Parent
records?
If this interpretation is correct, you can do the following:
public static List<Detail__c> findSiblings(List<Child__c> children)
{
Set<Id> parentIds = new Set<Id>();
for (Child__c child : children) parentIds.add(child.Parent__c);
return [SELECT Id FROM Detail__c WHERE Parent__c IN :parentIds];
}
Another interpretation I could see is:
How can I find all Detail
records whose Parent
has any Child
records?
If this interpretation is correct, I would add a field on Parent
along the lines of Has_Child_Records__c
, which you can manage from Process Builder
. Just set it up on Child
to update the Parent
checkbox with the criteria OR(ISNEW(), ISCHANGED(Parent__c))
. Then you can just do:
public static List<Detail__c> findDetails()
{
return [SELECT Id FROM Detail__c WHERE Parent__r.Has_Child_Records__c = true];
}
If neither of these interpretations is correct, please add more detail to your question to clarify.
X
records whoseY
has any childZ
records? Or you already have someZ
records and you are looking forX
records that look up to theirY
parents? Or something else entirely?Z
is a (lookup) child ofY
andY
is a (detail) child ofX
, then to traverse from X to Z requires two SOQL queries (X + Ys) and (Ys + Zs)X
is also a child ofY
.