public function beforeFind(Event $event, Query $query, $options, $primary) { if ($query->clause('limit') == 1) { return $query; } foreach ($this->orderBy() as $field => $ord) { $f = $this->aliasField($field); $query->order([$this->aliasField($field) => $ord]); } if (!is_array($this->primaryKey())) { return $query; } $query->sql(); // force evaluation of internal state/objects foreach ($query->clause('join') as $join) { if (!$this->association($join['table'])) { continue; } $table = TableRegistry::get($join['table']); $table->alias($join['alias']); foreach ($table->orderBy() as $field => $ord) { $query->order([$table->aliasField($field) => $ord]); } } return $query; }
/** * Gets a list of all virtual columns present in given $query's SELECT clause. * * This method will alter the given Query object removing any virtual column * present in its SELECT clause in order to avoid incorrect SQL statements. * Selected virtual columns should be fetched after query is executed using * mapReduce or similar. * * @param \Cake\ORM\Query $query The query object to be scoped * @param string|null $bundle Consider attributes only for a specific bundle * @return array List of virtual columns names */ public function getVirtualColumns(Query $query, $bundle = null) { static $selectedVirtual = []; $cacheKey = md5($query->sql()) . '_' . $bundle; if (isset($selectedVirtual[$cacheKey])) { return $selectedVirtual[$cacheKey]; } $selectClause = (array) $query->clause('select'); if (empty($selectClause)) { $selectedVirtual[$cacheKey] = array_keys($this->_toolbox->attributes($bundle)); return $selectedVirtual[$cacheKey]; } $selectedVirtual[$cacheKey] = []; $virtualColumns = array_keys($this->_toolbox->attributes($bundle)); foreach ($selectClause as $index => $column) { list($table, $column) = pluginSplit($column); if ((empty($table) || $table == $this->_table->alias()) && in_array($column, $virtualColumns)) { $selectedVirtual[$cacheKey][$index] = $column; unset($selectClause[$index]); } } if (empty($selectClause) && !empty($selectedVirtual[$cacheKey])) { $selectClause[] = $this->_table->primaryKey(); } $query->select($selectClause, true); return $selectedVirtual[$cacheKey]; }