Get records from a related object in Lightning Web Component

|
| By Webner

Problem: Suppose we have an object with a lookup field and we want to fetch a record with related object data in Lightning Web Component.

Solution: We can get a record of the object directly in the LWC JS code. We can do it by using uiRecordApi in the Lightning Web Component js file.

Example:
import { LightningElement, track, wire } from 'lwc';
import { getRecord } from "lightning/uiRecordApi";
const FIELDS = [
"objectAPIName.objectFieldName",
"objectAPIName.relatedObjectAPIName__r.relatedObjectFieldName"
];
export default class ComponentName extends LightningElement {
objectRecords;
relatedObjectRecords;
@wire(getRecord, {
recordId: "$recordId",
fields: FIELDS
})
acordFormDetails(result) {
if (typeof result.data !== "undefined") {
this.objectRecords = result.data.fields;
this.relatedObjectRecords = this.objectRecords.relatedObjectAPIName__r.value
.fields.relatedObjectFieldName.value;
}
}
}

Leave a Reply

Your email address will not be published. Required fields are marked *