I have 3 content type "A" , "B", "C". B has a node reference to A. C has a node reference to B.


Using simple query I want to get the master parent node Id of C. which is A node id


How to do this.

  • what have you previously tried? are you looking for a DB query for use in a custom module?
    – Mike Miles
    Oct 17, 2012 at 16:56

1 Answer 1


If you are looking for a DB query within a custom module, you could do something like the following example function that recursively goes through the reference tree to get to the top for a node. It will work for N levels, (but not for multi-valued references or nodes with multiple node reference fields).

function mymodule_getTopReference($nid){
    $top_nid = 0;
    //load the node
    $node = node_load($nid);
    //get all reference fields
    $node_reference_fields = array();
    $field_infos = field_info_instances('node',$node->type);
    foreach ($field_infos as $field_name=>$value){
        $field = field_info_field($field_name);
        if (($field['type'] == 'node_reference')){
            if ($field_value = field_get_items('node',$node,$field['field_name'])){
                $top_nid = $field_value[0]['nid'];

    if ($top_nid && ($parent_nid = mymodule_getTopReference($top_nid))){
        $top_nid = $parent_nid;
    return $top_nid;

For example, if your node reference field was called "my_reference" and your example nodes had the following nids:

  • A = 1
  • B = 2
  • C = 3

and your references are as you said:

  • B->A (2->1)
  • C->B (3->2)

Then for node 'C'(3) you'd call this function like so:

$top_nid = mymodule_getTopReference(3);

which then would set $top_nid to 1 (A's nid).

  • yeah I am looking for a query within a custom module. This is exactly what I wanted. Thank you so much.
    – Cindrella
    Oct 18, 2012 at 4:31
  • Its only working for 3 level node reference. Not for 4 level nodereference say D->B->C->A. wanted A. node reference fields are called by different names in every content type. Any idea for this.
    – Cindrella
    Oct 18, 2012 at 6:31
  • Ahh I did not realize you were dealing with different reference fields across different node types. I have updated my code accordingly and it should work, I tested with 4 levels. this is also a more 'drupal' method since we are not doing any direct db querying and are relying on drupals core functions.
    – Mike Miles
    Oct 18, 2012 at 12:09
  • @Mike Miles:Thank you so much. Its Working Perfectly.
    – Cindrella
    Oct 18, 2012 at 12:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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