Are you an LLM? You can read better optimized documentation at /before-update/add-ons/related-query.md for this page in Markdown format
BeforeUpdate.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, BeforeUpdate.RecordsProvider> queryRelatedOnBeforeUpdate();
}queryRelatedOnBeforeUpdate(): called at most once per handler per run, at this handler’s firstgetRelated. Returns provider name →RecordsProvider.
Example
apex
public with sharing class ContactPopulator implements BeforeUpdate.Populator, BeforeUpdate.RelatedQuery {
public Map<String, BeforeUpdate.RecordsProvider> queryRelatedOnBeforeUpdate() {
return new Map<String, BeforeUpdate.RecordsProvider>{ 'accountContacts' => new AccountContactsProvider() };
}
public Boolean populateOnBeforeUpdateWhen(TriggerTypes.UpdateRecord record) {
return record.isChanged(Contact.AccountId);
}
public void populateOnBeforeUpdate(TriggerTypes.UpdateRecord record) {
Id accountId = ((Contact) record.getNewSObject()).AccountId;
record.put(Contact.Description, 'Contacts on the account: ' + record.getRelated('accountContacts').getAllWhereKeyEquals(accountId).size());
}
private with sharing class AccountContactsProvider implements BeforeUpdate.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;
}
}
}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
- SOQL sees the saved values. A query on the records being updated returns their values from before this update. Two records in one chunk that change to the same email do not find each other; compare them in a Finalizer.
- Exclude the records themselves. To look at other records of the same object, add
Id NOT IN :records.getIds(). - Keys match exactly. Key lookups are case-sensitive. Normalize text keys the same way in
keyOfand in the lookup. - Runs on every pass that reads it. In each chunk and nested update, a provider queries when the handler first calls
getRelatedwith its name. A read in a predicate queries even when no record qualifies.
WARNING
The provider sets the sharing. Its SOQL runs under the provider class's own sharing keyword. Use without sharing when a check must see every record.
