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, 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.
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.
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.
Display the records using the for:each
directive.