function nodereference_count_get_count in Nodereference Count 6
Same name and namespace in other branches
- 7 nodereference_count.module \nodereference_count_get_count()
Get the count of nodereferences to a node.
Parameters
$field: the field array for this field instance
$nid: the nid of the node being referenced
Return value
a count of the number of references to the node
2 calls to nodereference_count_get_count()
- nodereference_count_field in ./
nodereference_count.module - Implementation of cck hook_field().
- nodereference_count_update_count in ./
nodereference_count.module - Update the count of nodereferences to a node when not updating via CCK.
File
- ./
nodereference_count.module, line 113 - Defines a field type for counting the references to a node.
Code
function nodereference_count_get_count($field, $nid) {
// We want to allow aggregate counts from multiple fields referencing this node
// so we get the list of fields to count from the field array and then loop through
// creating a sql statement for each field.
$referencing_fields = $field['referenceable_fields'];
$queries = array();
$count_by_status = $field['referenceable_fields_count_by_status'];
foreach ($referencing_fields as $referencing_field) {
if ($referencing_field) {
$db_info = content_database_info(content_fields($referencing_field));
$table = $db_info['table'];
$column = $db_info['columns']['nid']['column'];
// Not sure a placeholder would work for the nid in this context.
// It should be safe regardless as it is getting the value from the node object in CCK or hook_nodeapi().
if ($count_by_status == 'published') {
$queries[] = "SELECT COUNT(DISTINCT content.vid) FROM {" . $table . "} AS content, {node} AS node WHERE " . $column . " = " . $nid . " AND node.vid = content.vid AND node.status = 1";
}
else {
$queries[] = "SELECT COUNT(DISTINCT nid) FROM {" . $table . "} WHERE " . $column . " = " . $nid;
}
}
}
// There is probably a better way to do this. For now we create a set of subqueries
// getting a count for each referencing field and adding those together.
// For the most common case of a single referencing field being counted we pass the query directly.
$query_count = count($queries);
if ($query_count == 1) {
$sql = $queries[0];
}
else {
$sql = "SELECT ";
for ($i = 0; $i < $query_count; $i++) {
$sql .= $i > 0 ? " + " : "";
$sql .= "(" . $queries[$i] . ")";
}
$sql .= " AS nr_count";
}
return db_result(db_query($sql));
}