---
url: https://trigger.beyondthecloud.dev/after-update/add-ons/related-query.md
description: >-
  Query children, siblings or any other records once per handler per run in an
  after update Writer or Dispatcher, and read them per record by key.
---

# 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 first `getRelated`. Returns provider name → `RecordsProvider`.

**Example**

::: code-group

```apex [Skeleton]
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 \[Children by AccountId]
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 \[Open opportunities]
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 {#records-provider}

**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 first `getRelated` with its name, with every record in the chunk. Returns the rows to index by key; `null` counts as no rows.
* `keyOf(row)`: called once per row that `query` returned. Returns the key that `getFirstWhereKeyEquals` and `getAllWhereKeyEquals` match; `null` leaves the row out of the index.

## Rules {#rules}

* **Read your own providers by name.** Call `record.getRelated('contacts').getAllWhereKeyEquals(record.getId())`. An unknown name throws `TriggerTypes.TriggerLibException`, even with ContinueOnError.
* **Keys match exactly, case included.** Normalize text keys the same way in `keyOf` and in the lookup.
* **Providers run on the first read.** A provider queries when the handler first calls `getRelated` with its name. A read in a predicate queries even when nothing qualifies, so return an empty list from `query` when no record can qualify.
* **Both rows.** `records.getIdsOf(…)` reads the new rows and `records.getOldIdsOf(…)` the old ones. SOQL sees the saved new values. Add `Id 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.
:::
