Sort Node Queries by an entity reference field within a field collection item I am trying to fetch a list of nodes of a particular content type, alongside their field-collection items. The code below works perfectly for my use case.

    function report_cards_get_term_data($type, $term, $session, $student_id, $class){
    $resarr = array(); 
    $query = db_select('node', 'n');
    $query-&gt;join('field_data_field_term', 'ft', 'n.nid = ft.entity_id');
    $query-&gt;join('field_data_field_session', 'dfs', 'n.nid = dfs.entity_id');
    $query-&gt;join('field_data_field_admission_number', 'rn', 'n.nid = rn.entity_id');
    $query-&gt;join('field_data_field_result', 'fr', 'n.nid = fr.entity_id');
    $query-&gt;join('field_data_field_class', 'cg', 'n.nid = cg.entity_id');
    $query-&gt;join('field_data_field_subject', 'cfs', 'cfs.entity_id = fr.field_result_value');    
    $query-&gt;join('field_data_field_exam_score', 'ces', 'ces.entity_id = fr.field_result_value');
    $query-&gt;join('field_data_field_first_ca', 'cfc', 'cfc.entity_id = fr.field_result_value');
    $query-&gt;join('field_data_field_second_ca', 'csc', 'csc.entity_id = fr.field_result_value');
    $query-&gt;fields('cfs');
    $query-&gt;condition('n.type', $type);
    $query-&gt;condition('field_term_value', array('1st Term', '2nd Term', '3rd Term'), 'IN');
    $query-&gt;condition('field_session_target_id', $session);
    $query-&gt;condition('field_class_target_id', $class);  
    $query-&gt;condition('field_admission_number_target_id', $student_id);
    $query-&gt;addExpression('cfc.field_first_ca_value + csc.field_second_ca_value + ces.field_exam_score_value', 'total');
    //$query-&gt;orderBy('cfs.field_subject_target_id-&gt;weight', 'ASC');
    $report_card = $query-&gt;execute();
}


However, i need to sort the result alphabetically by the entity reference name (taxonomy term) called "Subject". The entity reference is a field within the field collections. I know i can use "$query->orderBy()" but i can't get it to work. That's why it was commented out in the given code above. 
Thank you for your suggestions.
Solved it myself. I added one more join, 

$query-&gt;join('taxonomy_term_data', 'fee', 'cfs.field_subject_target_id = fee.tid'); 

Then order by 

$query-&gt;orderBy('fee.name', 'ASC');


Then the result was ordered alphabetically by the taxonomy name.