2

I have a Parent1__C,Parent2__c and a Juntion__c object. Junction object has master-detial relation ship with both parents.

I am writing a trigger on parent2__c where my requirement is to get the Parent1__c records in a List. I have traverse the relationship like Parent2__c->Junction__c->Parent1__c. I am also looking at a bulkified approach so that it does not hit the governors limit.

My thoughts: This may not be the right approach so any suggestion is appreciated. In the end I am trying to build a list of Parent1__c record that are related to Parent2__c.

Map<ID,List<Junction__c>> aMap = new Map<ID,List<Junction__c>>();

// not sure how can I get the List<Junction__c> here?
for(Parent2__C p:trigger.new){
aMap.put(p.id,how to get the Junction List here?);
}

List<Parent1__c> pare1 = new List<Parent1__c>();

for(Parent2__c p:trigger.new){
// how can I get Parent1__c record from aMap and add it to Parent2__c?
}
1

1 Answer 1

5

Option 1

// Create a map
Map<Id, Parent1__c[]> parent1 = new Map<Id, Parent1__c[]>();
// Prefill to avoid null pointers
for(Parent2__c record: Trigger.new) {
    parent1.put(record.Id, new Parent1__c[0]);
}
// Get Parent1__c records
for(Junction__c record: [SELECT Parent2__c, Parent__r.Name, ... FROM Junction__c WHERE Parent2__c IN :Trigger.new]) {
    parent1.get(record.Parent2__c).add(record.Parent1__r);
}

The end result will be a Map with a key for each Parent2__c record Id, with a list of zero or more Parent1__c records. This code discards the Junction__c records, but if you need those, you could just as easily store them in a map instead.

This uses one fewer query limits in exchange for CPU time (uses more time than below).

Option 2

Map<Id, Parent2__c> records = new Map<Id, Parent2__c>(
    [SELECT (SELECT Parent1__c, Parent1__r.Name ... FROM Junctions__r)
     FROM Parent2__c WHERE Id IN :Trigger.new]
);

This results in a map where each Parent2__c has a child list of records in Junctions__r (refer to your Junction's master-detail field for the correct relationship name), including Parent1__c details stored in Parent1__r.

This method uses one more aggregate query limit (three times the top-level query limit) in exchange for CPU time (uses less CPU time than the option above).

1
  • This is great. Really appreciate your effort to provide an optimal answer. Thanks!
    – SfdcBat
    Commented Nov 2, 2016 at 5:10

You must log in to answer this question.

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