Read relatedList Record in LWC
In most of the cases we might need to read related records of particular parent records.
The usual way we follow is apex to read the related records. But LWC offers a related list api to fetch the related data using parent recordId.
The lightning/uiRelatedListApi module includes wire adapters to get related list metadata and record data. The wire adapters are:
- getRelatedListInfo
- getRelatedListsInfo
- getRelatedListRecords
- getRelatedListCount
- getRelatedListRecordsBatch
- getRelatedListInfoBatch
The related list api wire adapter have some parameters there are,
Parameters
- parentRecordId – (Required) The ID of the parent record that you want to get related lists for, like an Account ID.
- relatedListId – (Required) The API name of a related list object, like Contacts, Opportunities, or Cases.
- fields – (Optional) The API names of the related list’s column fields.
- optionalFields – (Optional) The API names of additional fields in the related list.
- pageSize – (Optional) The number of list records to return per page.
- sortBy – (Optional) An array of field API names to sort the related list by. Accepts only one value per request.
- where – (Optional) The filter to apply to related list records, in GraphQL syntax.
relatedRecord.Html
<template>
<lightning-card title=”wireGetRelatedListRecords”>
<template if:true={records}>
<table class=”slds-table”>
<tr>
<th>Id</th>
<th>Name</th>
</tr>
<template for:each={records} for:item=”rec”>
<tr key={rec.fields.Id.value}>
<td>{rec.fields.Id.value}</td>
<td>{rec.fields.Name.value}</td>
</tr>
</template>
</table>
</template>
</lightning-card>
  </template>
relatedRecord.js
import { LightningElement,wire,api,track } from 'lwc';
import { getRelatedListRecords } from "lightning/uiRelatedListApi";
export default class RelatedList extends LightningElement {
@api recordId;
error;
records;
@wire(getRelatedListRecords, {parentRecordId: "0035j00000vYntwAAC",
relatedListId: "Bank__r", fields: ['Bank__c.Name','Bank__c.Id']
},)
const({ error, data }) {
if (data) {
this.records = data.records;
this.error = undefined;
}else if (error) {
this.error = error;
this.records = undefined;
}
}
}
Output:
