/** * Alters the SQL to apply LIMIT and OFFSET. * @param string $sql SQL query string without LIMIT and OFFSET. * @param integer $limit maximum number of rows, -1 to ignore limit. * @param integer $offset row offset, -1 to ignore offset. * @return string SQL with LIMIT and OFFSET */ public function applyLimit($sql, $limit, $offset) { // Ugly, but this is how MySQL recommends doing it: https://dev.mysql.com/doc/refman/5.0/en/select.html if ($limit <= 0 && $offset > 0) { $limit = PHP_INT_MAX; } return parent::applyLimit($sql, $limit, $offset); }
/** * Creates the SQL statement. * @param CDbCommandBuilder $builder the command builder * @return CDbCommand DB command instance representing the SQL statement */ public function createCommand($builder) { $sql = ($this->distinct ? 'SELECT DISTINCT ' : 'SELECT ') . implode(', ', $this->selects); $sql .= ' FROM ' . implode(' ', $this->joins); $conditions = array(); foreach ($this->conditions as $condition) { if ($condition !== '') { $conditions[] = $condition; } } if ($conditions !== array()) { $sql .= ' WHERE (' . implode(') AND (', $conditions) . ')'; } $groups = array(); foreach ($this->groups as $group) { if ($group !== '') { $groups[] = $group; } } if ($groups !== array()) { $sql .= ' GROUP BY ' . implode(', ', $groups); } $havings = array(); foreach ($this->havings as $having) { if ($having !== '') { $havings[] = $having; } } if ($havings !== array()) { $sql .= ' HAVING (' . implode(') AND (', $havings) . ')'; } $orders = array(); foreach ($this->orders as $order) { if ($order !== '') { $orders[] = $order; } } if ($orders !== array()) { $sql .= ' ORDER BY ' . implode(', ', $orders); } $sql = $builder->applyLimit($sql, $this->limit, $this->offset); $command = $builder->getDbConnection()->createCommand($sql); $builder->bindValues($command, $this->params); return $command; }