I finally have the Ids query corrected(after 20 years);

Select (Select ParentA__c From ChildA__r) 
From ParentB s 
WHERE Id IN (Select s.ParentB 
From ChildB s)

I now have the IDs I would need to populated the lookup field in ChildB.

The criteria would be if the ParentB Id of ChildB (Master-Detail) field = ParentB Id of ChildA ( Master Detail ) field


Get ParentA Id of that ChildA and populate the ParentA Id Lookup up field in ChildB.

( Hope it made a lot of sense )

enter image description here

Now the issue is I cannot get it to materialize.

Hope this is simple enough for a favor to ask.

How would you code this? Specially the Upsert part?

  • #sfdcfox, please help? thanks ! – JOE Jun 17 '14 at 1:26
  • So you have a Lookup Field on ChildB that you want to populate with the Id of ParentA? Where are you starting from? I.e. Are you currently dealing with a collection of ChildB records? – Daniel Ballinger Jun 17 '14 at 3:02
  • Yes, Yes ! I am really dumb on these so I really appreciate your help on this. – JOE Jun 17 '14 at 3:17

Assign your existing query result to a Map. This will allow you to quickly get the ParentB__c records by Id. Then you can access the ChildAs ParentA ID from the ChildA__r list.

Map<Id, ParentB__c> parentBsMap = new Map<Id, ParentB__c>([Select Id, (Select ParentA__c From ChildA__r) 
From ParentB__c s 
WHERE Id IN (Select s.ParentB__c From ChildB__c s)]);

for(ChildB cb : yourCollectionOfChildBRecords) {
     if(parentBsMap.containsKey(cb.ParentB__c)) {
         ParentB__c pb = parentBsMap.get(cb.ParentB__c);
         List<ChildA__c> cas = pb.ChildA__r;
         if(cas.size() > 0) {
             Id firstParentAId = cas[0].ParentA__c;
             // Set you lookup field here
             cb.ParentALookup__c = firstParentAId;
  • Oh My GOD ! It worked @Daniel Ballinger. I big big THANK YOU ! You and fishofprey.com rocks BIG TIME !!! – JOE Jun 19 '14 at 4:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.