Ordering content

@param Builder $query
@param array $availableFields
@return mixed
432551
protected function orderData(Builder $query, array $availableFields)
    {
        $sortBy = request()->input('sort_by');
        $sortOrder = request()->input('sort_order');

        if (in_array($sortBy, $availableFields))
            if (in_array(strtolower($sortOrder), ['asc', 'desc']))
                return $query->orderBy($sortBy, $sortOrder);

        return $query->orderBy('created_at', 'desc');
    }
422786
public function fieldSelect($table, $fields, $where, $orderBy = null)
    {
        $table = $this->getTableName($table);

        $query = "SELECT ";

        if (substr($this->mode, 0, 5) === "mssql") {
            $query .= "TOP 1 ";
        }

        $query .= $this->selectFields($fields);

        $query .= " FROM " . $table . " ";

        $params = null;
        if ($where !== self::NO_WHERE_CLAUSE) {
            $query .= "WHERE " . $this->where($where, $params);
        }

        if ($orderBy) {
            $query .= $this->orderBy($orderBy) . " ";
        }

        switch ($this->mode) {

            case "mysql":
            case "postgres":
            case "redshift":
            case "sqlite":
                $query .= "LIMIT 1";
                break;

            case "odbc":
                $query .= "FETCH FIRST 1 ROW ONLY";
                break;
        }

        return $this->query($query, $params)->fetch();
    }
104873
private function applyFilters(AbstractQueryBuilder $query)
    {
        //GroupBy is only applicable to Select
        if ($query instanceof Select) {
            if (isset($this->groupByFields)) {
                $query->groupBy($this->groupByFields);
            }
            $this->joinRelationsToQuery($this->entity, $query, $this->with);
        }
        if (isset($this->where)) {
            $query->where($this->where);
        }
        foreach ($this->orderByFields as $field) {
            list($fieldName, $order) = $field;
            $query->orderBy($fieldName, $order);
        }
        if (empty($this->with)) {
            //Limits for joined queries are handled in a different way
            if (isset($this->limit)) {
                $query->setMaxResults($this->limit);
            }
            if (isset($this->offset)) {
                $query->setFirstResult($this->offset);
            }
        }

        return $query;
    }
112282
public function scopeSortable($query, $key = null, $direction = null)
    {
        list($key, $direction) = $this->validateSortableParameters($key, $direction);

        if ($this->isTranslationAttribute($key))
        {
            return $this->orderByTranslationAttribute($query, $key, $direction);
        }

        return $query->orderBy($key, $direction);
    }
207058
public function scopeOrder(Builder $query)
    {
        if ($order = config('typicms.'.$this->getTable().'.order')) {
            foreach ($order as $column => $direction) {
                $query->orderBy($column, $direction);
            }
        }

        return $query;
    }
1047596
protected function getResults($query)
    {
         $searchFields = ($this->getSearchFields() ?: singleton($this->sourceObject)->stat('searchable_fields'));

        if(!$searchFields) {
            throw new Exception(
                sprintf('HasOneAutocompleteField: No searchable fields could be found for class "%s"',
                $this->sourceObject));
        }

        $params = [];
        $sort = [];
        
        foreach($searchFields as $searchField) {
            $name = (strpos($searchField, ':') !== FALSE) ? $searchField : "$searchField:PartialMatch:nocase";
            $params[$name] = $query;
            $sort[$searchField] = "ASC";
        }

        $results = DataList::create($this->sourceObject)
            ->filterAny($params)
            ->sort($sort)
            ->limit($this->getResultsLimit());

        return $results;
    }
1311603
public function orderBy($field, $direction = self::DESC) {
        if (is_array($field)) {
            foreach ($field as $key => $dir) {
                $this->orderBy($key, $dir);
            }

        } else if ($field === 'RAND') {
            $this->_orderBy[] = $this->func('RAND');

        } else if ($field instanceof Func) {
            $this->_orderBy[] = $field;

        } else {
            $direction = strtolower($direction);

            if ($direction != self::ASC && $direction != self::DESC) {
                throw new InvalidArgumentException(sprintf('Invalid order direction %s for field %s', $direction, $field));
            }

            $this->_orderBy[$field] = $direction;
        }

        return $this;
    }
382569
private function queryOrderBuilder($query, array $sortParameters)
    {
        $model = $this;

        list($column, $direction) = $this->parseParameters($sortParameters);

        if (is_null($column)) {
            return $query;
        }

        $explodeResult = SortableLink::explodeSortParameter($column);
        if ( ! empty($explodeResult)) {
            $relationName = $explodeResult[0];
            $column       = $explodeResult[1];

            try {
                $relation = $query->getRelation($relationName);
                $query    = $this->queryJoinBuilder($query, $relation);
            } catch (BadMethodCallException $e) {
                throw new ColumnSortableException($relationName, 1, $e);
            } catch (\Exception $e) {
                throw new ColumnSortableException($relationName, 2, $e);
            }

            $model = $relation->getRelated();
        }

        if (method_exists($model, camel_case($column).'Sortable')) {
            return call_user_func_array([$model, camel_case($column).'Sortable'], [$query, $direction]);
        }

        if (isset($model->sortableAs) && in_array($column, $model->sortableAs)) {
            $query = $query->orderBy($column, $direction);
        } elseif ($this->columnExists($model, $column)) {
            $column = $model->getTable().'.'.$column;
            $query  = $query->orderBy($column, $direction);
        }

        return $query;
    }
727338
protected function compileOrders(Builder $query, $orders)
    {
        if (empty($orders)) {
            return '';
        }

        return 'order by '.implode(', ', array_map(function ($order) {
            if (isset($order['sql'])) {
                return $order['sql'];
            }

            return $this->wrap($order['column']).' '.$order['direction'];
        }, $orders));
    }
374764
protected function compileOrders(Builder $query, $orders)
    {
        if (! empty($orders)) {
            return 'order by '.implode(', ', $this->compileOrdersToArray($query, $orders));
        }

        return '';
    }
1016436
def _make_order(field_path, direction):
        """"""
        return query_pb2.StructuredQuery.Order(
            field=query_pb2.StructuredQuery.FieldReference(field_path=field_path),
            direction=_enum_from_direction(direction),
        )
616830
public function run($query)
    {
        $options = $this->options;
        $count = $query->getCountForPagination();

        if (!$options['limit']) {
            $options['page'] = 1;
        } elseif ($options['page'] < 1 || $options['page'] > ceil($count / $options['limit'])) {
            $options['page'] = 1;
        }

        $order = false;
        $direction = false;
        if (!empty($options['order'])) {
            if (is_array($options['order'])) {
                foreach ($options['order'] as $order_column) {
                    if (!empty($options['sort'][$order_column])) {
                        $order = $order_column;
                        if (isset($options['direction']) && strtolower($options['direction']) == 'desc') {
                            $direction = 'desc';
                            $query->orderBy($options['sort'][$order_column], 'DESC', true);
                        } else {
                            $direction = 'asc';
                            $query->orderBy($options['sort'][$order_column], 'ASC', true);
                        }
                    }
                }
            } else {
                if (!empty($options['sort'][$options['order']])) {
                    $order = $options['order'];
                    if (isset($options['direction']) && strtolower($options['direction']) == 'desc') {
                        $direction = 'desc';
                        $query->orderBy($options['sort'][$options['order']], 'DESC', true);
                    } else {
                        $direction = 'asc';
                        $query->orderBy($options['sort'][$options['order']], 'ASC', true);
                    }
                }
            }
        }
        // Add order by unique key
        if ($query instanceof \Globalis\PuppetSkilled\Database\Magic\Builder) {
            $isOrdering = !empty($query->getQuery()->orders);
        } else {
            $isOrdering = !empty($query->orders);
        }

        if ($isOrdering) {
            $query->orderBy($options['unique_order_key']);
        }

        if (!empty($options['limit_choices']) && !in_array($options['limit'], $options['limit_choices'])) {
            $options['limit'] = current($options['limit_choices']);
        }
        if (!empty($options['limit'])) {
            $query->limit($options['limit']);
            $query->offset(($options['page']-1) * $options['limit']);
        }

        $page = $options['page'];
        $limit = $options['limit'];

        if (!$options['limit']) {
            $pageCount = 1;
        } else {
            $pageCount = (int)ceil($count / $limit);
        }
        $this->result =  [
            'result'        => $query->get(),
            'page'          => $page,
            'total'         => $count,
            'perPage'       => $limit,
            'prevPage'      => ($page > 1),
            'nextPage'      => ($count > ($page * $limit)),
            'pageCount'     => $pageCount,
            'sort'          => $order,
            'direction'     => $direction,
            'limit'         => $limit,
            'limit_choices' => $options['limit_choices'],
        ];
        return $this->result;
    }
521993
public function scopeRecentlyCreated(Builder $query, $limit = null)
    {
        $query->orderBy('created_at', 'desc');

        if ($limit)
        {
            $query->limit($limit);
        }

        return $query;
    }
151132
public function buildQuery(Builder $query = null): Builder
    {
        $query = $this->getSubQuery($this->meta, $query, $this->conditions['rules'], $this->conditions['condition']);

        if ($this->offset > 0) {
            $query->offset($this->offset);
        }
        if ($this->limit > 0) {
            $query->limit($this->limit);
        }

        return $query;
    }
889498
public static function buildWheres(QueryInterface $query, array $conditions, $allowNulls = true)
    {
        foreach ($conditions as $key => $value) {
            // NULL
            if ($value === null && $allowNulls) {
                $query->where($query->format('%n IS NULL', $key));
            } elseif ($value instanceof Compare) {
                // If using Compare class, we convert it to string.
                $query->where((string) static::buildCompare($key, $value, $query));
            } elseif (is_numeric($key)) {
                // If key is numeric, just send value to query where.
                $query->where($value);
            } elseif (is_array($value) || is_object($value)) {
                // If is array or object, we use "IN" condition.
                if ($value instanceof \Traversable) {
                    $value = iterator_to_array($value);
                } elseif (is_object($value)) {
                    $value = get_object_vars($value);
                }

                $value = array_map([$query, 'quote'], $value);

                $query->where($query->quoteName($key) . new QueryElement('IN ()', $value, ','));
            } else {
                // Otherwise, we use equal condition.
                $query->where($query->format('%n = %q', $key, $value));
            }
        }

        return $query;
    }
1273286
public static function getOrder($sort, $allowField, $mapped = [], $defaultOrder = '')
    {
        $order = $defaultOrder;
        if ($sort) {
            $orders = [];
            $sortData = json_decode($sort, true);
            foreach ($sortData as $item) {
                if (!empty($item) && isset($item['property']) && isset($item['direction'])) {
                    $fieldName = $item['property'];
                    if (isset($mapped[$fieldName])) {
                        $fieldName = $mapped[$fieldName];
                    }
                    if (in_array($fieldName, $allowField)) {
                        $order = $fieldName;
                        if ('DESC' == $item['direction']) {
                            $order .= ' DESC';
                        } else {
                            $order .= ' ASC';
                        }
                        $orders[] = $order;
                    }
                }
            }
            if ($orders) {
                $order = join(',', $orders);
            }
        }

        return $order;
    }
425794
protected function orderByMapped(Builder $query, ArgumentBag $args, $table, $column, $target)
    {
        $query->with($target)->getQuery()->orderBy("{$table}.{$column}", $args->get('direction'));

        return $query;
    }