2

I have a junction object TargetxOpp which is a detail record, in Master-Detail Relationships with Opportunities & Targets.

I am retrieving the TargetxOpp records via an SOQL query, looping through a list of the parent Opportunities & adding the TargetxOpp to different lists.

for(Opportunity o : [SELECT Id, RecordTypeId,
                    (SELECT Id, Target__r.Date_Type__c
                       FROM TargetxOpp__r)
                       FROM Opportunity
                      WHERE (Id IN :reassignedOpps OR Id IN :oppsWNewCD OR Id IN :oppsWNewVerticals)])
                {
 >                if (o.TargetxOpp__r.Target__r.Date_Type__c == 'Created Date' &&
                      oppsWNewVerticals.contains(o.Id))
                      {
                        targetsToUpdate.add(o.TargetxOpp__r);
                      } else {
                        targetsToDel.add(o.TargetxOpp__r);
                  }
                }

When I try to evaluate the retrived TargetxOpp records on this line (I've added a > pointing to the line in the above code) -

if (o.TargetxOpp__r.Target__r.Date_Type__c == 'Created Date' &&

Note - that object does not have an 's' as it's plural label or the child relationship name for the lookup to the Opportunity.

I hit an error -

Invalid foreign key relationship: Opportunity.TargetxOpp__r

& I assume that, that's because the query is retrieving a list of TargetxOpp records, rather than a single record.

I know that I could add those records to a list & then work through them but I'd rather not use a 2nd for loop to do so & I'm hoping that I can assess the TargetxOpp child records within the above query's for loop instead. Is this possible or is the for loop not cycling through the retrieved child records too?

1 Answer 1

3

The child records are a collection, so you cannot reference properties on that List<SObject> as if they were a single record. You can iterate:

for (Opportunity record : [/*query*/])
{
    for (Opportunity child : record.TargetxOpp__r)
    {
        if (child.Target__r.Date_Type__c == 'Created Date')
        {
            // do stuff
        }
    }
}
0

You must log in to answer this question.

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