8

I have two custom objects. One parent, one child. I am using an inner query to obtain records.

for(objectA__c obA: [select id, myfieldA__c, (select id, myfieldB__c from objectB__r) from objectA__c)]{

//Perform some code here


}

I am receiving 'Invalid foreign key relationship when I attempt to use the following:

obA.objectB__r.myfieldB__c

How do I reference myfieldB__c on objectB__c????

I've looked at documentation on standard objects and it makes sense but I can't seem to get this to work on custom objects.

0

1 Answer 1

10

The inner query return a list of records so you need to iterate throughout them taking into account how to process the records if multiple records are in the returned result. What to do depends on your use case

for(objectA__c obA: [select id, myfieldA__c, (select id, myfieldB__c from objectB__r) from objectA__c)]{

   For(ObjectB__c b : oba.ObjectB__r){
      //Access the field from the record taking into account there could be multiple results in this loop
      PROPERTY/FIELD/ETC = b.myfieldb__c;
   }


}

If however ChildB is a detail of a master, no need to do the inner select as you can simply pull the field via

objecA__c.ObjectB__r.myfield__c

but your query would be different:

[Select ID, objectb__r.myfieldb__c From Objecta__c]
1
  • Makes perfect sense and both ways work great. Thanks for the examples.
    – Berg
    Jun 24, 2015 at 17:52

You must log in to answer this question.

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