Query Multiple Objects Dynamically

GraphQL API simplifies how you query records across multiple objects. You can write a query that asks for the exact fields you want in one call. Using GraphQL API to query multiple objects is more performant than making multiple Apex wire calls. Previously, you could also achieve this by calling a custom Apex controller and then pass the returned records to the getRecords wire adapter with additional parameters that request records from other objects.

Additionally, when statically defined, GraphQL API queries support referential integrity for references to objects and fields. You don’t need to import references to objects and fields like you do with other LWC wire adapters.

Use GraphQL Variables in Multiple Objects Query 

When you request records across multiple objects, you don’t always know the record ID. For example, the record ID can vary depending on the record page you’re viewing, or the user ID can depend on the context user. To provide the record ID as a dynamic value for your query, use the variables configuration parameter.

The graphqlMultipleObjects component in the lwc-recipes repo retrieves and displays account and contact records using a single query.

Tip

This example queries all contacts related to an account and displays the contacts with record data from the User object. The query requests the Id and Name fields on the Contact object, along with the Id and Name fields on the User object.

The AccountId field on the Contact object corresponds to the ID of an account record. Use the recordId property to include the account record context for the contacts query.

To get record data about the current user, import the @salesforce/user/Id module.

1//multipleObjectsGraphQL.js
2import { LightningElement, wire, api } from "lwc";
3import { gql, graphql } from "lightning/graphql";
4import Id from "@salesforce/user/Id";
5
6export default class MultipleObjectsGraphQL extends LightningElement {
7  queryError;
8  contacts;
9
10  @api recordId;
11
12  userName;
13  userId = Id;
14
15  @wire(graphql, {
16    query: "$contactQuery",
17    variables: "$queryData",
18  })
19  recordsQueryResult({ data, errors }) {
20    if (data) {
21      this.contacts = data.uiapi.query.Contact.edges.map((edge) => edge.node);
22      this.userName = data.uiapi.query.User.edges.map((edge) => edge.node);
23    }
24
25    if (errors) {
26      this.queryError = errors;
27    }
28  }
29
30  get contactQuery() {
31    return gql`
32      query contactsOnAccount($recordId: ID!, $userId: ID!) {
33        uiapi {
34          query {
35            Contact(where: { AccountId: { eq: $recordId } }) {
36              edges {
37                node {
38                  Id
39                  Name {
40                    value
41                  }
42                }
43              }
44            }
45            User(where: { Id: { eq: $userId } }) {
46              edges {
47                node {
48                  Id
49                  Name {
50                    value
51                  }
52                }
53              }
54            }
55          }
56        }
57      }
58    `;
59  }
60
61  get queryData() {
62    return {
63      recordId: this.recordId,
64      userId: this.userId,
65    };
66  }
67}

Display the records using the for:each directive.

1<template>
2  <lightning-card title="MultipleObjectsGraphQL" icon-name="standard:contact">
3    <div class="slds-var-m-around_medium">
4      <template lwc:if={contacts}>
5        <template for:each={contacts} for:item="contact">
6          <p key={contact.Id}>{contact.Name.value}</p>
7        </template>
8      </template>
9      <template lwc:if={userName}>
10        <template for:each={userName} for:item="user">
11          <p key={user.Id}>{user.Name.value}</p>
12        </template>
13      </template>
14
15      <template lwc:elseif={errors}>
16        <!-- Display errors -->
17      </template>
18    </div>
19  </lightning-card>
20</template>

See Also 

Query Objects Examples

Call Apex Methods

GraphQL API Query Limitations