In this LWC a GraphQL query contains unrelated objects in the same query.
Please be aware that in this LWC those related are Account and Contact, which are not unrelated, as contacts are related to Accounts, but in this example are treated as unrelated.
<aside> ๐ก If not familiar with how to use the GraphQL wire adapter, review this section: Using GraphQL in LWC and with wire adapter and also : Querying multiple unrelated objects, and finally this section Querying multiple related objects.
</aside>
<aside>
๐ You can find the component in this folder: force-app\\main\\default\\lwc\\graphqlMultipleObjects
</aside>
When using the GraphQL wire adapter, some imports
are required:
import { gql, graphql } from 'lightning/uiGraphQLApi';
The syntax for using the wire adapter is the same as in the previous recipe, with the only difference that here we are adding a second object to retrieve in the same query:
export default class GraphqlMultipleObjects extends LightningElement {
@wire(graphql, {
query: gql`
query getAccountAndContacts {
uiapi {
query {
Account(first: 5) {
edges {
node {
Id
Name {
value
}
}
}
}
**Contact(first: 5) {
edges {
node {
Id
Name {
value
}
}
}
}**
}
}
}
`
})
graphqlVar; //this variable has been renamed to avoid confusion with the library imported with the same name
The results from the query execution are stored in the graphqlVar
, and the 2 getter functions allow to return the contacts and the accounts obtained:
get accounts() {
return this.graphqlVar.data?.uiapi.query.Account.edges.map((edge) => ({
Id: edge.node.Id,
Name: edge.node.Name.value
}));
}
get contacts() {
return this.graphqlVar.data?.uiapi.query.Contact.edges.map((edge) => ({
Id: edge.node.Id,
Name: edge.node.Name.value
}));
}
The template becomes even simpler as non child object is used, but instead, the record values for both objects are displayed directly to the user:
...
<template lwc:if={accounts}>
<div class="slds-var-m-around_medium">
<b>Accounts:</b>
<template for:each={accounts} for:item="account">
<div key={account.Id} class="accounts">
<p>{account.Name}</p>
</div>
</template>
</div>
</template>
...
...
<template lwc:if={contacts}>
<div class="slds-var-m-around_medium">
<b>Contacts:</b>
<template for:each={contacts} for:item="contact">
<div key={contact.Id} class="contacts">
<p>{contact.Name}</p>
</div>
</template>
</div>
</template>
...
LWC RecordPickerBasic (Custom)
Did you find an issue/mistake? You donโt like something? Do you have external content that I should link to improve the learning process? Did you find it helpful? Any of those are super valuable to me. So, please write me at [email protected], and promise to answer.
<aside> โ๏ธ Jump to the main page: The LWC Recipes Cookbook
</aside>