I have a content type student, and it has an Entity Reference field named as field_offline_course_reference and a email field field_offline_course_student_ema

I need a list of all emails of students based on field_offline_course_reference value.

How can I change the following code to achieve what I want to do?

$courseinfo = $theCourseId;    
$query = db_select('node', 'n');

$query->join("field_data_field_offline_course_reference", "t", "t.entity_id = n.nid");
$query->fields("n", array("nid"))
    ->condition('n.type', 'students')
    ->condition('t.entity_id', $courseinfo);

$result = $query->execute();
    foreach ($result as $record) {
  • you just want get nid here. really do you know what you wrote or what you want?
    – Yuseferi
    May 29, 2016 at 13:31
  • i need the email actually which is "field_offline_course_student_ema" field.
    – brainHax
    May 29, 2016 at 13:32

1 Answer 1


You need to JOIN on nid and vid (entity fields are stored per nid/vid), add a JOIN to your email field table, set the fields to select the email value, and set your WHERE clause to entity reference target.

$query = db_select('node', 'n');
$query->join("field_data_field_offline_course_reference", "t", "t.entity_id = n.nid AND t.revision_id = n.vid");
$query->join("field_data_field_offline_course_student_ema", "e", "e.entity_id = n.nid AND e.revision_id = n.vid");
$query->fields("e", array("field_offline_course_student_ema_value"))
    ->condition('n.type', 'students')
    ->condition('t.field_offline_course_reference_target_id', $courseinfo);
  • Thaknk you @Shwan Conn
    – brainHax
    Jun 1, 2016 at 10:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.