Retrieve Many-to-Many (N:N) Relationship Records using Web API in Dynamics 365 using JavaScript
The below code can be used when you want to read N:N or many-to-many related records and do some logics for validations. As N:N intersect table cannot be found in Advance Find you can check the name of intersect table from powerapps solution.
The below code runs on a command button click and checks if a related records of the current records having some field value and alerting accordingly.
function VarifyStudentReward(executionContext)
{
var recordId = executionContext.data.entity.getId();
var fetchXmlQuery = "<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='true'>"+
"<entity name='soft_reward'>"+
"<attribute name='soft_name' />"+
"<attribute name='soft_category' />"+
"<order attribute='soft_name' descending='false' />"+
"<link-entity name='soft_reward_soft_student' from='soft_rewardid' to='soft_rewardid' visible='false' intersect='true'>"+
"<link-entity name='soft_student' from='soft_studentid' to='soft_studentid' alias='ab'>"+
"<attribute name='soft_name' />"+
"<attribute name='soft_phonenumber' />"+
"<filter type='and'>"+
"<condition attribute='soft_studentid' operator='eq' value='"+recordId+"' />"+
"</filter>"+
"</link-entity>"+
"</link-entity>"+
"<filter type='and'>"+
"<condition attribute='soft_category' operator='in'>"+
"<value>408260001</value>"+
"<value>408260000</value>"+
"</condition>"+
"</filter>"+
"</entity>"+
"</fetch>";
var globalContext = Xrm.Utility.getGlobalContext();
var req = new XMLHttpRequest();
req.open(
"GET",
globalContext.getClientUrl() +
"/api/data/v9.2/soft_rewards?fetchXml=" +
encodeURIComponent(fetchXmlQuery),
true
);
req.setRequestHeader("Prefer", 'odata.include-annotations="*"');
req.onreadystatechange = function() {
if (this.readyState === 4) {
req.onreadystatechange = null;
if (this.status === 200) {
var results = JSON.parse(this.response);
if(results.value.length >= 1)
alert("You are a top student");
else
alert("You are not a top student");
} else {
alert(this.statusText);
}
}
};
req.send();
}
hope this helps.
Follow my blog for more trending topics on Dynamics 365, Azure, C#, Power Portals and Power Platform. For training, Courses and consulting, call to us at +91 832 886 5778 I am working more for community to share skills in Dynamics 365 and Power Platform. Please support me by subscribing my YouTube Channel. My YouTube Channel link is this : https://www.youtube.com/user/sppmaestro