function _views_query::query in Views (for Drupal 7) 5
File
- ./
views_query.inc, line 570
Class
Code
function query($getcount = false) {
$table_data = _views_get_tables();
// Set distinct
if (!$this->no_distinct && $this->distinct && count($this->fields)) {
$field = $this->fields[0];
$this->fields[0] = "DISTINCT({$field})";
$this->count_field = "DISTINCT({$this->count_field})";
//this is only needed once
$this->no_distinct = TRUE;
}
// Add all the tables to the query via joins. We assume all LEFT joins.
foreach ($this->tablequeue as $tinfo) {
$table = $tinfo['table'];
// The real table name may differ from what we're calling it.
$table_real = isset($table_data[$table]['name']) ? $table_data[$table]['name'] : $table;
$table_num = $tinfo['num'];
$table_alias = $this
->get_table_name($table, $table_num, $tinfo['alias_prefix']);
$joininfo = !$this->joins[$table][$table_num] ? $table_data[$table]['join'] : $this->joins[$table][$table_num];
$left_table_alias = isset($joininfo['left']['alias']) ? $joininfo['left']['alias'] : $tinfo['alias_prefix'];
$left_table_alias .= $joininfo['left']['table'];
// the { is a special character which seems to be treated differently
// in PHP5 than PHP4 so we do this a little oddly.
$join_type = $joininfo['type'] == 'inner' ? 'INNER' : 'LEFT';
$joins .= " {$join_type} JOIN {" . $table_real . "} {$table_alias} ON " . $left_table_alias . "." . $joininfo['left']['field'] . " = {$table_alias}." . $joininfo['right']['field'];
if (isset($joininfo['extra'])) {
foreach ($joininfo['extra'] as $field => $value) {
$joins .= " AND {$table_alias}.{$field}";
if (is_array($value) && count($value)) {
$joins .= " IN ('" . implode("','", $value) . "')";
}
else {
if ($value !== NULL) {
$joins .= " = '{$value}'";
}
}
}
}
}
// If it's not a count query, add our fields
if (!$getcount) {
$fields = implode(', ', $this->fields);
// we only add the groupby if we're not counting.
if ($this->groupby) {
$groupby = "GROUP BY " . implode(', ', $this->groupby);
}
// ok, tablesort_sql is really, really (really) annoying.
// 1) it insists on adding the ORDER BY clause.
// 2) You're supposed to give it your stuff as $before, but
// 3) You have to add the comma and
// 4) if it doesn't have anything to add, it returns NOTHING.
// 5) So I'm just going to get what it sends back and chop off
// the orderby, cause otherwise my code is too ugly with
// various checks.
if ($this->header) {
$result = tablesort_sql($this->header);
if ($result) {
$this->orderby[] = str_replace('ORDER BY ', '', $result);
}
}
if ($this->orderby) {
$orderby = "ORDER BY " . implode(', ', $this->orderby);
}
}
else {
$fields = "count({$this->count_field})";
}
if ($this->where) {
$where = "WHERE (" . implode(') AND (', $this->where) . ')';
}
$query = "SELECT {$fields} FROM {" . $this->primary_table . "} {$this->primary_table} {$joins} {$where} {$groupby} {$orderby}";
$replace = array(
'>' => '>',
'<' => '<',
);
$query = strtr($query, $replace);
return $query;
}