Are you an LLM? You can read better optimized documentation at /before-insert/add-ons/related-query.md for this page in Markdown format
BeforeInsert.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, BeforeInsert.RecordsProvider> queryRelatedOnBeforeInsert();
}queryRelatedOnBeforeInsert(): 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 BeforeInsert.Populator, BeforeInsert.RelatedQuery {
public Map<String, BeforeInsert.RecordsProvider> queryRelatedOnBeforeInsert() {
return new Map<String, BeforeInsert.RecordsProvider>{ 'accountContacts' => new AccountContactsProvider() };
}
public Boolean populateOnBeforeInsertWhen(TriggerTypes.InsertRecord record) {
return record.isNotNull(Contact.AccountId);
}
public void populateOnBeforeInsert(TriggerTypes.InsertRecord 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 BeforeInsert.RecordsProvider {
public List<SObject> query(TriggerTypes.InsertRecords records) {
return [SELECT Id, AccountId FROM Contact WHERE AccountId IN :records.getIdsOf(Contact.AccountId)];
}
public String keyOf(SObject row) {
return ((Contact) row).AccountId;
}
}
}apex
public with sharing class ContactDuplicateEmailValidator implements BeforeInsert.Validator, BeforeInsert.RelatedQuery {
public Map<String, BeforeInsert.RecordsProvider> queryRelatedOnBeforeInsert() {
return new Map<String, BeforeInsert.RecordsProvider>{ 'existingContacts' => new ExistingContactsProvider() };
}
public Boolean addErrorOnBeforeInsertWhen(TriggerTypes.InsertRecord record) {
Contact newContact = (Contact) record.getNewSObject();
return record.isNotBlank(Contact.Email) && record.getRelated('existingContacts').getFirstWhereKeyEquals(newContact.Email.toLowerCase()) != null;
}
public void addErrorOnBeforeInsert(TriggerTypes.RejectableInsertRecord record) {
record.addError(Contact.Email, 'A contact with this email already exists.');
}
private without sharing class ExistingContactsProvider implements BeforeInsert.RecordsProvider {
public List<SObject> query(TriggerTypes.InsertRecords records) {
return [SELECT Id, Email FROM Contact WHERE Email IN :records.getValuesOf(Contact.Email)];
}
public String keyOf(SObject row) {
return ((Contact) row).Email?.toLowerCase();
}
}
}RecordsProvider
Signature
apex
public interface RecordsProvider {
List<SObject> query(TriggerTypes.InsertRecords 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
- No Ids yet.
records.getIds()is empty. Filter by field values withrecords.getValuesOf(…)or by lookups withrecords.getIdsOf(…). - SOQL cannot see this save. The new records are not in the database yet. Compare them with each other in a Populator's Finalizer.
- Keys match exactly, case included. Normalize text keys the same way in
keyOfand in the lookup, as[Duplicate email]does withtoLowerCase(). - Providers query 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.
WARNING
Each provider has its own sharing. Declare a keyword on every provider class; an inner class does not inherit it. A with sharing duplicate check misses records the user cannot see.
