Skip to content

Instantly share code, notes, and snippets.

@Paulmicha
Created February 14, 2013 09:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Paulmicha/4951673 to your computer and use it in GitHub Desktop.
Save Paulmicha/4951673 to your computer and use it in GitHub Desktop.
Drupal 7 helper functions : get nodes referring to a given nid through a given entity reference field, and the same, but filtered by type
<?php
/**
* Drupal 7 helper functions for Entity Reference fields
*
* @author Paulmicha
* @version 0.1
*/
/**
* Get nodes referring to a given nid through a given entity reference field
*/
function get_referencing_content( $nid, $field_entity_ref )
{
$return = array();
$safe_field_name = preg_replace( '`[^a-z_]`', '', $field_entity_ref );
if ( !empty( $nid ) && !empty( $safe_field_name ))
{
$query = "SELECT node.title AS node_title, node.nid AS nid, node.created AS node_created
FROM {node} node
LEFT JOIN {field_data_$safe_field_name} field_data_$safe_field_name ON node.nid = field_data_$safe_field_name.entity_id AND ( field_data_$safe_field_name.entity_type = 'node' AND field_data_$safe_field_name.deleted = '0' )
INNER JOIN {node} node_field_data_$safe_field_name ON field_data_$safe_field_name.". $safe_field_name ."_target_id = node_field_data_$safe_field_name.nid
WHERE node_field_data_$safe_field_name.nid = :nid
ORDER BY node_created DESC";
$result = db_query( $query, array( ':nid' => $nid ));
foreach( $result as $record )
$return[ $record->nid ] = $record->node_title;
}
return $return;
}
/**
* Get nodes referring to a given nid through a given entity reference field, filtered by node type
*/
function get_referencing_content_by_type( $nid, $field_entity_ref, $type )
{
$return = array();
$safe_field_name = preg_replace( '`[^a-z_]`', '', $field_entity_ref );
if ( !empty( $nid ) && !empty( $safe_field_name ))
{
$query = "SELECT node.title AS node_title, node.nid AS nid, node.created AS node_created
FROM {node} node
LEFT JOIN {field_data_$safe_field_name} field_data_$safe_field_name ON node.nid = field_data_$safe_field_name.entity_id AND ( field_data_$safe_field_name.entity_type = 'node' AND field_data_$safe_field_name.deleted = '0' )
INNER JOIN {node} node_field_data_$safe_field_name ON field_data_$safe_field_name.". $safe_field_name ."_target_id = node_field_data_$safe_field_name.nid
WHERE node_field_data_$safe_field_name.nid = :nid
AND node.type = :node_type
ORDER BY node_created DESC";
$result = db_query( $query, array( ':nid' => $nid, ':node_type' => $type ));
foreach( $result as $record )
$return[ $record->nid ] = $record->node_title;
}
return $return;
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment