4
function mymodule_get_nodes_by_user_referencing_nid($type, $userid, $referncenid) {
    return node_load_multiple(array(), array('type' => $type, 'uid' => $userid, ??? => ???));
}

I need a function that lists nodes by following this logic: give me all nodes of a given type which are created by a given user and which have a node reference field referencing a given node id.

Any ideas about such function (in PHP, not in Views) )?

2 Answers 2

5

This code assumes you're using the entityreference module using field name "field_reference":

$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node');
$query->propertyCondition('type', $type);
$query->propertyCondition('uid', $userid);
$query->fieldCondition('field_reference', 'target_id', $referenceid);
$result = $query->execute();

$nodes = array();
if (!empty($result['node'])) {
  $nodes = node_load_multiple(array_keys($result['node']));
}
0
4

The EntityFieldQuery class was made for just that:

$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', $type)
  ->properyCondition('uid', $user_id)
  ->fieldCondition('field_name_of_field', 'target_id', $nid);

$results = $query->execute();

if (!empty($results['node'])) {
  $nodes = node_load_multiple(array_keys($results['node']));
}

Note that target_id is the name of the column for an Entity Reference field; if you're using the References module it will be nid instead.

0

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.