Search code examples
dynamics-crm-2011odata

Dynamics CRM Odata Query one entity and a related entity-- but also a relation between the 2nd entity and a 3rd


So I have 3 custom entities... Patient, PatientDiagnosis and Diagnosis

Patients can have multiple PatientDiagnosis linked to the Patient by a GUID for the PatientID.

The PatientDiagnosis records are related to the Diagnosis entity I'm using JavaScript to query the web services for Dynamics CRM 2011.

I want to get some patient info and the list of patientDiagnosis, but I also want a field or two stored in the Diagnosis table.

I can easily query the Patient and PatientDiagnosis entities... but I can't figure out how to tie the N:1 relationship from PatientDiagnosis to Diagnosis in the same query.

http://........../2011/OrganizationData.svc/new_participantSet(guid'{blah blah blah}')?
$select=new_new_participant_new_participantdiagnosis/new_PrimaryDiagnosis
,new_new_participant_new_participantdiagnosis/new_Active
,new_ReferralSource
,new_Location
,<<<<new_diagnosis/ID>>>>    //I'd like to include Diagnosis entity data too//
&$expand=new_new_participant_new_participantdiagnosis

Solution

  • You can do this in 2 ways.

    1) you can use the expand parameter (aka $select=[stuff]&$expand=[stuff]) - looks like you were on the right track for this one OR

    2) you can nest a 2nd query within the 1st query's successcallback

    I prefer to use the CRMRestKit to simplify my OData calls, so 1 would look something like this:

    var filter = 'new_participantid eq guid\'' + id + '\'';
    var DiagnosisField, PatientDiagnosisField;
    CRMRestKit.ByExpandQuery('PatientDiagnosis',['new_ReferralSource','x/new_Active'], x, filter) <-- x is the exact relationship name
    .done(function(data){
        DiagnosisField = data.d.results[0].x.results[0].new_Active;
        PatientDiagnosisField = data.d.results[0].new_ReferralSource;
    )
    

    and 2 would look like this:

    var DiagnosisField, PatientDiagnosisField;
    CRMRestKit.Retrieve('PatientDiagnosis',GUID,[PColumns]).done(function(data){ <--Patient Diagnosis Columns here
        CRMRestKit.Retrieve(['Diagnosis',data.d.DiagnosisLookup.Id,[DColumns]]).done(function(data2){ <-- Diagnosis columns here
            PatientDiagnosisField = data.d.[field from patient diagnosis];
            DiagnosisField = data2.d.[field from diagnosis];
        });
    )};