function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
softcloud2009softcloud2009 

using trigger.new

To prevent the soql query limit on triggers, i would like to replace this line of code:

 

for (Order_Detail__c orderDetail :trigger.new) 
    {

         Id acctID = orderDetail.Account__c;
         Account account = [select Id, parentId from Account where Id = :acctID limit 1];
         Id parentAccountId = account.parentId;

    }

 

with this one:

 

for (Order_Detail__c orderDetail :trigger.new) 
    {

         Id parentAccountId = Trigger.newMap.get(orderDetail.Id).Account__r.ParentId;

    }

 

However, I got an error attempt to de-reference a null object.

 

 


        
       

Message Edited by softcloud2009 on 05-27-2009 12:01 AM
Divya GoelDivya Goel

I apex you can not get the value of related data without quering the related data.

In the following ex. Account__r is null object.

 Id parentAccountId = Trigger.newMap.get(orderDetail.Id).Account__r.ParentId;

 

Better way to do yoor code is:

 Set <ID> setOrderId = new set<ID>();

 

for (Order_Detail__c orderDetail :trigger.new) 
    {

       setOrderId.add(orderDetail.Account__c);

                

    }

 Account [] accounts = [select Id, parentId from Account where Id in :setOrderId];

for(Account a: accounts ){
         Id parentAccountId = a.parentId;

}

softcloud2009softcloud2009
I tried that method but it causes the soql query to be called exceed the limit. Is there any other way to retrieve the data without exceed the governance limit. Thanks.
BritishBoyinDCBritishBoyinDC

You need to put into  orderDetail.Account__c into a Set as demonstrated, but then put the results of the Select statement into a map : Map<ID, Account> m = new Map<ID, Account>([select id, parentid from Account where id in :accids]);

 

Then you loop through the trigger again and use the value in orderDetail.Account__c field to look up the key field in the map to return the parent Id using the get method for the map.