Are you an LLM? You can read better optimized documentation at /after-update/add-ons/related-query.md for this page in Markdown format
AfterUpdate.RelatedQuery
Query children, siblings or other records once per handler per run, and read them per record with record.getRelated(name).
Signature
apex
public interface RelatedQuery {
Map<String, AfterUpdate.RecordsProvider> queryRelatedOnAfterUpdate();
}queryRelatedOnAfterUpdate(): called at most once per handler per run, at this handler’s firstgetRelated. Returns provider name →RecordsProvider.
Example
apex
public with sharing class ContactWriter implements AfterUpdate.Writer, AfterUpdate.RelatedQuery {
public Map<String, AfterUpdate.RecordsProvider> queryRelatedOnAfterUpdate() {
return new Map<String, AfterUpdate.RecordsProvider>{ 'accountContacts' => new AccountContactsProvider() };
}
public Boolean writeOnAfterUpdateWhen(TriggerTypes.UpdateRecord record) {
return record.isChanged(Contact.AccountId);
}
public void writeOnAfterUpdate(TriggerTypes.UpdateRecord record, TriggerTypes.UnitOfWork unitOfWork) {
Id accountId = ((Contact) record.getNewSObject()).AccountId;
Integer contactCount = record.getRelated('accountContacts').getAllWhereKeyEquals(accountId).size();
unitOfWork.toInsert(new Task(WhatId = accountId, Subject = 'Contacts on the account: ' + contactCount));
}
private with sharing class AccountContactsProvider implements AfterUpdate.RecordsProvider {
public List<SObject> query(TriggerTypes.UpdateRecords records) {
return [SELECT Id, AccountId FROM Contact WHERE AccountId IN :records.getIdsOf(Contact.AccountId)];
}
public String keyOf(SObject row) {
return ((Contact) row).AccountId;
}
}
}cls
public with sharing class AccountAddressCascadeWriter implements AfterUpdate.Writer, AfterUpdate.RelatedQuery, AfterUpdate.ContinueOnError, AfterUpdate.RecursionGuard {
public Integer maxRunsPerRecordOnAfterUpdate() {
return 1;
}
public Map<String, AfterUpdate.RecordsProvider> queryRelatedOnAfterUpdate() {
return new Map<String, AfterUpdate.RecordsProvider>{ 'contacts' => new AccountContactsProvider() };
}
public Boolean writeOnAfterUpdateWhen(TriggerTypes.UpdateRecord record) {
return record.isAnyChanged(Account.BillingStreet, Account.BillingCity, Account.BillingState, Account.BillingPostalCode, Account.BillingCountry);
}
public void writeOnAfterUpdate(TriggerTypes.UpdateRecord record, TriggerTypes.UnitOfWork unitOfWork) {
Account newAccount = (Account) record.getNewSObject();
Account oldAccount = (Account) record.getOldSObject();
for (SObject row : record.getRelated('contacts').getAllWhereKeyEquals(record.getId())) {
Contact contact = (Contact) row;
if (!this.mailingFollowedAccount(contact, oldAccount)) {
continue;
}
unitOfWork.toUpdate(
new Contact(
Id = contact.Id,
MailingStreet = newAccount.BillingStreet,
MailingCity = newAccount.BillingCity,
MailingState = newAccount.BillingState,
MailingPostalCode = newAccount.BillingPostalCode,
MailingCountry = newAccount.BillingCountry
)
);
}
}
private Boolean mailingFollowedAccount(Contact contact, Account oldAccount) {
if (String.isBlank(contact.MailingStreet) && String.isBlank(contact.MailingCity)) {
return true;
}
return contact.MailingStreet == oldAccount.BillingStreet &&
contact.MailingCity == oldAccount.BillingCity &&
contact.MailingPostalCode == oldAccount.BillingPostalCode &&
contact.MailingCountry == oldAccount.BillingCountry;
}
private with sharing class AccountContactsProvider implements AfterUpdate.RecordsProvider {
public List<SObject> query(TriggerTypes.UpdateRecords records) {
return [
SELECT Id, AccountId, MailingStreet, MailingCity, MailingState, MailingPostalCode, MailingCountry
FROM Contact
WHERE AccountId IN :records.getIds()
];
}
public String keyOf(SObject row) {
return ((Contact) row).AccountId;
}
}
}cls
public with sharing class AccountOwnerTransferWriter implements AfterUpdate.Writer, AfterUpdate.ParentQuery, AfterUpdate.PriorParentQuery, AfterUpdate.RelatedQuery, AfterUpdate.Bypassable {
public static Boolean isBypassed = false;
public Boolean bypassOnAfterUpdateWhen() {
return AccountOwnerTransferWriter.isBypassed || System.isBatch();
}
public Map<SObjectField, TriggerTypes.ParentFields> queryParentsOnAfterUpdate() {
return new Map<SObjectField, TriggerTypes.ParentFields>{ Account.OwnerId => TriggerTypes.ParentFields.with(User.Name) };
}
public Map<SObjectField, TriggerTypes.ParentFields> queryPriorParentsOnAfterUpdate() {
return new Map<SObjectField, TriggerTypes.ParentFields>{ Account.OwnerId => TriggerTypes.ParentFields.with(User.Name) };
}
public Map<String, AfterUpdate.RecordsProvider> queryRelatedOnAfterUpdate() {
return new Map<String, AfterUpdate.RecordsProvider>{ 'openOpportunities' => new AccountOpenOpportunitiesProvider() };
}
public Boolean writeOnAfterUpdateWhen(TriggerTypes.UpdateRecord record) {
return record.isChanged(Account.OwnerId);
}
public void writeOnAfterUpdate(TriggerTypes.UpdateRecord record, TriggerTypes.UnitOfWork unitOfWork) {
Account newAccount = (Account) record.getNewSObject();
User oldOwner = (User) record.getOldParent(Account.OwnerId);
User newOwner = (User) record.getNewParent(Account.OwnerId);
String handoverNote = Date.today().format() + ' - account handed over from ' + oldOwner?.Name + ' to ' + newOwner?.Name;
for (SObject row : record.getRelated('openOpportunities').getAllWhereKeyEquals(record.getId())) {
Opportunity opportunity = (Opportunity) row;
unitOfWork.toUpdate(new Opportunity(Id = opportunity.Id, OwnerId = newAccount.OwnerId, Description = this.notedDescription(handoverNote, opportunity.Description)));
}
}
private String notedDescription(String handoverNote, String description) {
return String.isBlank(description) ? handoverNote : handoverNote + '\n' + description;
}
private with sharing class AccountOpenOpportunitiesProvider implements AfterUpdate.RecordsProvider {
public List<SObject> query(TriggerTypes.UpdateRecords records) {
return [
SELECT Id, AccountId, Description
FROM Opportunity
WHERE AccountId IN :records.getIds() AND IsClosed = FALSE
];
}
public String keyOf(SObject row) {
return ((Opportunity) row).AccountId;
}
}
}RecordsProvider
Signature
apex
public interface RecordsProvider {
List<SObject> query(TriggerTypes.UpdateRecords records);
String keyOf(SObject row);
}query(records): called once per provider, at the handler’s firstgetRelatedwith its name, with every record in the chunk. Returns the rows to index by key;nullcounts as no rows.keyOf(row): called once per row thatqueryreturned. Returns the key thatgetFirstWhereKeyEqualsandgetAllWhereKeyEqualsmatch;nullleaves the row out of the index.
Rules
- Read your own providers by name. Call
record.getRelated('contacts').getAllWhereKeyEquals(record.getId()). An unknown name throwsTriggerTypes.TriggerLibException, even with ContinueOnError. - Keys match exactly, case included. Normalize text keys the same way in
keyOfand in the lookup. - Providers run on the first read. A provider queries when the handler first calls
getRelatedwith its name. A read in a predicate queries even when nothing qualifies, so return an empty list fromquerywhen no record can qualify. - Both rows.
records.getIdsOf(…)reads the new rows andrecords.getOldIdsOf(…)the old ones. SOQL sees the saved new values. AddId NOT IN :records.getIds()to leave out the trigger records.
WARNING
Declare sharing on every provider class. An inner class does not take its outer class's keyword.
