+ Start a Discussion
micwamicwa 

Governor limits with SOQL in Triggers

If I have a Trigger on Acccount I can make:
Map<Id, Account>  m = Trigger.new;

and than I can select all Opportunities of those Accounts like that:
List<Opportunity> = [select o.Id from Opportunity where o.AccountId IN : m.keySet()];

But what do I do if I can't use the id of the trigger object, ex.

I have a trigger on Contracts and I want to select all the Accounts, i need something like:
Map<Id, Contract>  s = Trigger.new;
[select a.Id from Account c where a.Id IN :s.values().AccountId]
but this doesn't work, can someone help?
SuperfellSuperfell
Just walk the trigger.new array, and build your own array of ids.
List accIds = new List();
for(Contract c : trigger.new)
accIds.add(c.accountId);

// now do something with accIds


seems likely that the list contracts may have entries with for the same account, so you should probably build a set, and not a list,e.g.

Set accIds = new Set();
for(Contract c : trigger.new)
accIds.add(c.accountId);

// now do something with accIds
jyotijyoti

Try something like this:

  Set<Id> relatedAcctIds = new Set<Id>();

  for (Contract allContracts:Trigger.new)
  {
   relatedAcctIds.add(allContracts.AccountId);
  }

Then
List<Account> relatedAccounts = new List<Account>([select Id, Name from Account where AccountId in :relatedAcctIds limit 999]);