Created
July 15, 2018 05:56
-
-
Save quardz/64399dfe87f71caf5144c09b11791a7a to your computer and use it in GitHub Desktop.
Drupal entity reference get all the parents
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| //Get all the parent of a book as array | |
| function _book2_hlp_get_book_all_parents_array($entity_id, $table = 'node__field_book2_parent', | |
| $parent_field = 'field_book2_parent_target_id', $child_field = 'entity_id', | |
| $bundle = 'book2') { | |
| $output = array(); | |
| $node_relation = 'c.' . $child_field . ' = n.nid'; | |
| //Get all the childrens in sinle fetch, | |
| //For each fetch, get further children into recurssive | |
| $query = db_select($table, 'c'); | |
| $query->fields('c', array($parent_field, $child_field, 'bundle')); | |
| $query->addField('n', 'title'); | |
| $query->addField('n', 'status'); | |
| $query->addField('n', 'changed'); | |
| $query->join('node_field_data', 'n', $node_relation); | |
| //$query->condition('c.' . $parent_field, 'c.' . $child_field, '!='); | |
| $query->condition($child_field, $entity_id); | |
| if($bundle) { | |
| $query->condition('c.bundle', $bundle); | |
| } | |
| $query->condition('c.deleted', 0); | |
| $result = $query->execute()->fetchAllAssoc($child_field); | |
| if($result && count($result) && $entity_id) { | |
| foreach($result as $result) { | |
| $_pid = $result->{$parent_field}; | |
| $output[$result->{$child_field}] = $result; | |
| if($result->{$child_field} == $result->{$parent_field}) { | |
| return $output; | |
| } | |
| $_tmp_childs = _book2_hlp_get_book_all_parents_array($_pid, $table, $parent_field, $child_field, $bundle); | |
| if($_tmp_childs && count($_tmp_childs)) { | |
| foreach($_tmp_childs as $_tmp_child) { | |
| $_tmp_pid = $_tmp_child->{$child_field}; | |
| $output[$_tmp_pid] = $_tmp_child; | |
| } | |
| } | |
| //break; | |
| } | |
| } | |
| // Get the top most parent item | |
| else { | |
| if(!$entity_id) { | |
| return FALSE; | |
| } | |
| $query2 = db_select('node_field_data', 'n'); | |
| $query2->addField('n', 'title'); | |
| $query2->addField('n', 'status'); | |
| $query2->addField('n', 'changed'); | |
| $query2->addField('n', 'nid', $child_field); | |
| $query2->condition('nid', $entity_id); | |
| $result2 = $query2->execute()->fetchAllAssoc($child_field); | |
| if($result2 && count($result2)) { | |
| foreach($result2 as $_pid => $result2) { | |
| $output[$_pid] = $result2; | |
| $output[$_pid]->field_book2_parent_target_id = 0; | |
| $output[$_pid]->bundle = $bundle; | |
| } | |
| } | |
| } | |
| return $output; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment