Get contact object’s related Opportunity
When you have a master-detail relationship ( Contact to Opportunity) and want to get opportunities data on a contacts list page by using a custom component then you need to get each contact related opportunity.
Contact can have multiple opportunities for achieving this in the best scenario need to write a cascade SOQL query, this single query will return contacts and related opportunities.
Query for this: SELECT contact.Id, contact.Phone, contact.LastName, (SELECT Opportunity.Id, Opportunity.Name FROM contact.Opportunities) FROM contact
In the aura Component controller opportunity will be access like:
data.getReturnValue().forEach(function(key) {
console.log('Contact '+key.LastName);
if(key.Opportunities){
key.Opportunities.forEach(function(k, v) {
console.log('Opportunity '+k.Name);
});
}
});
and In the View file:
<ul class="slds-has-block-links_space">
<aura:iteration items="{!v.items}" var="item">
<li>
<h2><a>{!item.LastName}</a></h2>
<p>{!item.Phone}</p>
<br></br>
<p style="margin-left: 20px;">
<h3><b>Opportunities: </b></h3>
<ol>
<aura:iteration items="{!item.Opportunities}" var="data">
<li>{!data.Name}</li>
</aura:iteration>
</ol>
</p>
</li>
<br></br>
</aura:iteration>
</ul>
In a case if relationship don’t work then use prefix before object name in sub query, Like in NPSP package if we create a query with on recurring donation and try to get related donations then we have to wright it with prefix .npe03 is prefix here with donation lookup relation.
select id,(Select id from npe03__Donations__r) from npe03__Recurring_Donation__c
Generally it’s a good practice when we use prefix before object name