How to select nodes of a certain type, created by a certain user and which have reference field to a node equal a certain nid?
Solutions
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.
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']));
}