4

I have a Parent_Object__c with two string fields Number1__c and Number2__c. The Number2__c value for one record might be the same as Number1__c value for another record. My end goal is to populate two look-ups of Parent_Object__c on a Child_Object__c. The records of Child_Object__cis being created from external integration with Parent_Number1__c field.

Conditions to populate to those two look-ups are:

  1. Parent_Number1__c = Number1__c field of Parent_Object__c
  2. Once you get the above lookup, get the Number2__c field from that parent record and find another parent record that has the same Number1__c value.

On Child_Object__c trigger:

 set<string> parentNum1Values = new set<string>();
    for(Child_Object__c ch:Trigger.New)
    {
        parentNum1Values.add(ch.Parent_Number1__c);
    }
 set<string> parentNum2Values = new set<string>();

 map<string, string> Num1toNum2Map = new map<string, string>();
 map<string, Id> Num1LookUpMap = new map<string, Id>();
 map<string, Id> Num2LookupMap = new map<string, Id>();
    for(Parent_Object__c po:[select Id, Number1__c, Number2__c from Parent_Object__c 
                             where Number1__c IN :parentNum1Values])
    {
       if(po.Number1__c != po.Number2__c){
            parentNum2Values.add(po.Number2__c);
            Num1toNum2Map.put(po.Number1__c, po.Number2__c); //used when assigning lookups
       }

       Num1LookUpMap.put(po.Number1__c, po.Id);
    }
    for(Parent_Object__c po:[select Id from Parent_Object__c 
                             where Number1__c IN :parentNum2Values])
    {
       Num2LookupMap.put(po.Number1__c, po.Id);
    }

Can I refactor those two soql queries into one query?

  • No you can't join them into one. Not sure why you are getting down votes but you're not going to be able to simplify here. – Adrian Larson Mar 14 '18 at 18:55
  • 1
    I'd love to have comments on what is wrong with the question before down-voting. It helps me to ask them in the right way. – sam_s Mar 14 '18 at 18:56
  • 2
    @AdrianLarson Thank you. I know I voted for the right moderator :) – sam_s Mar 14 '18 at 18:57
  • 2
    Not sure what's with the downvotes, so I've upvoted to offset one of them. Does seem like more people are willing to downvote after someone else already has. – Derek F Mar 14 '18 at 18:58
4

You're stuck with two queries here. You can't use joins on any field type outside of relationships, and they don't work on hierarchical relationships either (same object as child and parent).

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.