5

I have an apex trigger that involves querying multiple objects. But I encounter this kind of error :

Error: Compile Error: A non foreign key field cannot be referenced in a path expression: ObjectBs__r

Here's a portion of the trigger where I encounter such error message:

Set<Id> objAid = new Set<Id>(); 
Set<Id> objDid = new Set<Id>();

for(ObjectC__c c : Trigger.new) {
        objAid.add(c.ObjectA__c);   
}

List<ObjectA__c> objAList = [SELECT Id, Name, (SELECT Id, Name, ObjectD__c FROM ObjectBs__r) FROM ObjectA__c WHERE Id IN: objAid];

for(ObjectA__c a : objAList[0].ObjectBs__r) {
        objDid.add(a.ObjectBs__r.ObjectD__c);
}
1
  • Does ObjectB__c have a relationship (master-detail, or lookup) to ObjectA__c? If it does, are you certain that ObjectBs__r is the correct child relationship name? (you can check by going to the detail page for the relationship field and looking for "child relationship name")
    – Derek F
    Commented Feb 26, 2018 at 13:45

2 Answers 2

4

ObjectBs__r in this case is a relationship name. When you perform a SOQL query that includes a subquery, as you do in this case:

[SELECT Id, Name, (SELECT Id, Name, ObjectD__c FROM ObjectBs__r) FROM ObjectA__c WHERE Id IN: objAid]

where (SELECT Id, Name, ObjectD__c FROM ObjectBs__r) is the subquery, you can treat the property ObjectBs__r as a List<ObjectB__c> in your Apex code.

The issue here is that you are indexing through a.ObjectBs__r.ObjectD__c as if ObjectBs__c were a lookup field containing the Id of a single ObjectB__c (a foreign key).

I'm not 100% confident of your data model based on the description given, but it looks to me like

objDid.add(a.ObjectBs__r.ObjectD__c);

should just be

objDid.add(a.ObjectD__c);

since a already comes from the ObjectBs__r list. a may also be declared as the wrong type in your for loop.

0
for(ObjectA__c a : objAList[0].ObjectBs__r) {
        objDid.add(a.ObjectBs__r.ObjectD__c);
}

Problem is here.

You're trying iterate over ObjectBs__r but you're delcaring a as ObjectA__c.

for(ObjectB__c a : objAList[0].ObjectBs__r) {
        objDid.add(a.Id);
}
1
  • This is a good catch. It's certainly an error, but I think this would generate a loop variable expected type <x> type error rather than the one OP is currently running in to.
    – Derek F
    Commented Feb 26, 2018 at 14:13

You must log in to answer this question.

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