RelatedRecords & RecordsProvider
A RecordsProvider queries related records once per handler per run: children, siblings, configuration or unrelated records. A handler returns its providers by name from its context's RelatedQuery add-on and reads them per record with record.getRelated('<provider name>').
RecordsProvider
Each context declares its own RecordsProvider, so query gets that context's collection. In after update:
Signature
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.Runs on the first read.
queryruns when the handler first callsgetRelatedwith the provider's name. Two handlers that use the same provider class query twice.Any query you like. Use inline SOQL, SOQL Lib or a selector.
Your sharing. The query runs under the provider class's own sharing keyword. Declare one on every provider class.
Parents load on the first read. In
query,records.getIdsOf('Account', Account.OwnerId)works.Normalize text keys. Keys are compared exactly, case included. Lowercase them in
keyOfand when you read.
RelatedRecords
What record.getRelated('<provider name>') returns.
Signature
public interface RelatedRecords {
SObject getFirstWhereKeyEquals(Object key);
List<SObject> getAllWhereKeyEquals(Object key);
List<SObject> getRecords();
Boolean isEmpty();
}| Method | Returns |
|---|---|
getFirstWhereKeyEquals(key) | the first row with that key, or null |
getAllWhereKeyEquals(key) | every row with that key; an empty list when there is none |
getRecords() | every row query returned, rows with a null key included |
isEmpty() | true when query returned no rows |
- Keys compare as text. An Id matches the same Id returned as a
StringfromkeyOf. - One index per provider, shared by the chunk. Look up by the current record, for example
getAllWhereKeyEquals(record.getId()). - Only your own providers.
getRelatedwith a name the handler did not return throws aTriggerLibException.
