Sub topic 8
Following relationships to parent and child records
Salesforce data is rarely flat. A contact belongs to an account, and an account has many contacts. This chapter shows how to cross those links in a single GraphQL query, so one wire call returns related records without extra Apex or extra requests.
This chapter assumes you have already read the earlier chapters in this tutorial. You should be comfortable with @wire(graphql), the edges and node structure, the value and displayValue wrappers, and reactive variables. You should also know the difference between a lookup field and a master-detail field.
Two directions, two shapes
The uiapi schema exposes both directions of a relationship as fields on a record's node.
- Parent direction (child to parent): a lookup or master-detail field gives you a single related record. The result is one object, not a list. Example: a Contact's
Account. - Child direction (parent to children): a child relationship gives you a list of related records. The result is a connection with its own
edgesandnode, just like a top-level query. Example: an Account'sContacts.
A parent field never has edges. A child field always does. If you remember only one rule from this chapter, remember that one.
How relationship fields are named
The names follow the Salesforce API names you already know.
| Relationship | Where it appears | Field name in the query | Shape |
|---|---|---|---|
| Standard lookup `AccountId` on Contact | Contact node | `Account` | Single record |
| Custom lookup `Region__c` on a custom object | That object's node | `Region__r` | Single record |
| Standard child relationship from Account to Contact | Account node | `Contacts` | Connection |
| Custom child relationship named `Invoices__r` | Parent node | `Invoices__r` | Connection |
The lookup field itself is still available under its own name, for example AccountId { value }. That gives you the ID as a field value. The relationship name without the Id suffix (Account) gives you the record, so you can select fields on it.
If you are unsure of a child relationship name, look at the Child Relationship name on the lookup field's definition in Setup, or in the object's reference documentation.
Reading a parent record
This query lists contacts and pulls the account name from the parent in the same request.
query contactsWithAccount {
uiapi {
query {
Contact(first: 10, orderBy: { LastName: { order: ASC } }) {
edges {
node {
Id
Name { value }
Account {
Id
Name { value }
Industry { value displayValue }
}
}
}
}
}
}
}Inside Account { ... } you select fields the same way you do at the top level. Each field is still wrapped, so you read node.Account.Name.value.
A contact may have no account. In that case Account is null, and reading node.Account.Name throws a TypeError. Always guard parent reads with optional chaining:
const accountName = node.Account?.Name?.value ?? 'No account';You can go up more than one level. Account { Owner { ... } } is valid. Every extra level adds cost against the query limits, so request only what the template shows.
Reading child records
Now go the other way. This component lists accounts and shows up to three contacts under each.
import { LightningElement, wire } from 'lwc';
import { gql, graphql } from 'lightning/uiGraphQLApi';
export default class AccountsWithContacts extends LightningElement {
accounts = [];
errors;
@wire(graphql, {
query: gql`
query accountsWithContacts($first: Int, $contactsFirst: Int) {
uiapi {
query {
Account(first: $first, orderBy: { Name: { order: ASC } }) {
edges {
node {
Id
Name { value }
Contacts(first: $contactsFirst, orderBy: { LastName: { order: ASC } }) {
edges {
node {
Id
Name { value }
Email { value }
}
}
}
}
}
}
}
}
}
`,
variables: '$variables'
})
wiredAccounts({ data, errors }) {
if (data) {
this.accounts = data.uiapi.query.Account.edges.map(({ node }) => ({
id: node.Id,
name: node.Name.value,
contacts: (node.Contacts?.edges ?? []).map(({ node: contact }) => ({
id: contact.Id,
name: contact.Name.value,
email: contact.Email.value
}))
}));
this.errors = undefined;
} else if (errors) {
this.errors = errors;
this.accounts = [];
}
}
get variables() {
return { first: 5, contactsFirst: 3 };
}
}Three details in this code matter.
- The child field takes its own arguments.
Contacts(first: $contactsFirst, orderBy: ...)limits and sorts the children for each account. This is separate from thefirstonAccount. - Variables can feed any level.
$contactsFirstis a query variable, so changing it reruns the whole query, as in the earlier chapter on reactive variables. - The mapping flattens twice. The outer
mapunwraps accounts. The innermapunwraps contacts. Doing this in the handler keeps the template free ofedgesandnode.
The matching template uses nested iteration. Each inner for:each needs its own key.
<template>
<lightning-card title="Accounts and contacts" icon-name="standard:account">
<template lwc:if={errors}>
<p class="slds-p-around_medium">The accounts could not be loaded.</p>
</template>
<template for:each={accounts} for:item="account">
<div key={account.id} class="slds-p-around_medium">
<h3 class="slds-text-heading_small">{account.name}</h3>
<ul>
<template for:each={account.contacts} for:item="contact">
<li key={contact.id}>{contact.name} ({contact.email})</li>
</template>
</ul>
</div>
</template>
</lightning-card>
</template>Filtering and sorting across relationships
Relationship fields work inside where as well as in the selection set. You can filter contacts by a field on the parent by nesting the parent field name in the filter:
Contact(
first: 10
where: { Account: { Industry: { eq: "Technology" } } }
) {
edges { node { Id Name { value } } }
}A filter on a child connection, such as Contacts(where: ...), only limits which children appear under each parent. It does not remove parents that have no matching children. The parent list is controlled by the where on the parent query. This surprises many developers: an account with zero matching contacts still appears, with an empty edges array.
Pagination and child lists
Each child connection can use first and also returns its own pageInfo, because it is a connection. Treat child lists as previews. A pattern that works well is to show the first few children on each parent, then navigate to a detail component that runs its own query for one parent's children with full paging. Deep nested paging inside one query is hard to manage, because every parent has its own cursor.
Keep the number of requested records in mind. The total work is roughly the number of parents times the number of children per parent. Asking for 50 accounts with 50 contacts each requests up to 2,500 contact records. Limits on depth and record counts are covered in the chapter on security behavior and limits, so keep nesting shallow and page sizes small now.
Common errors
Cannot read properties of nullon a parent field. The parent record is empty or not visible to the user. Guard with?..- Selecting
edgeson a parent field, or readingAccount.value. A parent relationship returns a record, so select its fields directly. - Treating a child field as a list.
node.Contactsis an object withedges. Usenode.Contacts.edges. - A missing field or object in the result with no thrown error. Field-level security or sharing can hide a related record. Partial results are described in the error handling chapter, so inspect the
errorsarray. - A wrong relationship name. A custom lookup
Region__cis selected asRegion__r, notRegion. A wrong name produces a validation error inerrors. - A missing
keyon the innerfor:each. LWC reports this at compile or render time. Use the record ID.
Summary of the working model
- Parent relationships return one record. Select fields directly inside them and guard against
null. - Child relationships return a connection. Read
edgesandnode, and give each connection its ownfirstandorderBy. - Flatten nested results in the wire handler so the template stays simple.
- A filter on a child connection limits the children, not the parents.
- Keep nesting shallow. Total records requested grows with each level.
Exercise
A query selects Account { Name { value } } on each Contact node and Contacts(first: 2) { edges { node { Id } } } on each Account node. For each of the two fields, say whether it returns a single object or a connection, and write the JavaScript expression that safely reads the account name from a contact node named node.
Show answer
Account on a Contact is a parent field and returns a single record, so you read its fields directly. Contacts on an Account is a child relationship and returns a connection, so you read node.Contacts.edges and then each edge's node. The safe expression for the account name is node.Account?.Name?.value, because the parent may be null when the contact has no account or the user cannot see it.
Exercise
You add where: { LastName: { like: "S%" } } to the Contacts(...) field under each Account. Some accounts have no contacts whose last name starts with S. Do those accounts still appear in the result? How would you hide them?
Show answer
Yes, they still appear, with an empty edges array, because a where on a child connection only limits the children. To hide them, filter the Account query itself, or filter out accounts whose Contacts.edges is empty in the wire handler before you build the list for the template.