@param QueryBuilder        $query
@param Model|SortableTrait $model

@return QueryBuilder
778669
protected static function applySortableGroup($query, $model)
    {
        $sortableGroupField = static::getSortableGroupField();

        if (is_array($sortableGroupField)) {
            foreach ($sortableGroupField as $field) {
                $query = $query->where($field, $model->$field);
            }
        } elseif ($sortableGroupField !== null) {
            $query = $query->where($sortableGroupField, $model->$sortableGroupField);
        }

        return $query;
    }
472644
protected function sort(ModelCriteria $query, Request $request)
    {
        $order = $this->getSortOrder($request);

        foreach ($order as $setting) {
            $column = $setting[0];
            $direction = $setting[1];
            $query->orderBy($column, $direction);
        }

        return $query;
    }
12639
public function beforeFind(Model $model, $query) {

		$runtime = $this->runtime[$model->alias];
		if ($runtime) {
			if (!is_array($query['conditions'])) {
				$query['conditions'] = array();
			}
			$conditions = array_filter(array_keys($query['conditions']));

			$fields = $this->_normalizeFields($model);

			foreach ($fields as $flag => $date) {
				if (true === $runtime || $flag === $runtime) {
					if (!in_array($flag, $conditions) && !in_array($model->name . '.' . $flag, $conditions)) {
						$query['conditions'][$model->alias . '.' . $flag] = false;
					}

					if ($flag === $runtime) {
						break;
					}
				}
			}
			return $query;
		}
	}
589250
protected function sortQuery(Builder $query, array $sort_order_options, Model $temp_instance, array $columns)
	{
		$allowed_directions = [
			'ASC',
			'DESC',
		];

		foreach ($sort_order_options as $order_by => $direction) {
			if (in_array(strtoupper($direction), $allowed_directions)) {
				$split = explode(self::GLUE, $order_by);

				// Sorts deeper than the depth restriction + 1 are not allowed
				// Depth restriction is offset by 1 because sorts terminate with a column
				// i.e. 'users.posts.title' => 'asc' but the depth we expect is 'users.posts'
				if (count($split) > ($this->getDepthRestriction() + 1)) {
					// Unset the disallowed sort
					unset($sort_order_options[$order_by]);
					continue;
				}

				if (in_array($order_by, $columns)) {
					$query->orderBy($order_by, $direction);
				} else {
					// Pull out orderBy field
					$field = array_pop($split);

					// Select only the base table fields, don't select relation data. Desired relation data
					// should be explicitly included
					$base_table = $temp_instance->getTable();
					$query->selectRaw("$base_table.*");

					$this->applyNestedJoins($query, $split, $temp_instance, $field, $direction);
				}
			}
		}
	}
1203724
protected function createFindQuery(): QueryBuilder
    {
        $query = $this->connection->createQueryBuilder();
        $query
            ->select('id', 'locale', 'name', 'disabled')
            ->from('ezcontent_language');

        return $query;
    }
795052
public function applyToQuery(Builder $query)
    {
        $this->query = $query;

        foreach ($this->request->all() as $filter => $value) {
            $method = Str::camel($filter);

            if ($this->filterCanBeApplied($method, $value)) {
                call_user_func([$this, $method], $value);
            }
        }

        return $query;
    }
886198
public function pagination($page, $limit, $query = null, $orderBy = null, $sort = 'ASC', $filter = null)
    {
        $entityClassAlias = $this->getEntityClassAlias();

        // Create a Doctrine Collection
        $queryBuilder = $this->getObjectManager()->createQueryBuilder();
        $queryBuilder->select($entityClassAlias)
                     ->from($this->getEntityClass(), $entityClassAlias);

        $paramCounter = 0;

        if (is_array($filter)) {
            $paramCounter = $this->addFilterToQueryBuilder($filter, $queryBuilder);
        }

        //Add joins to query builder
        $this->addJoinTablesToQueryBuilder($queryBuilder);

        if (null !== $query) {
            $properties    = $this->getQueryableProperties();
            $orExpressions = array();
            $paramCounter++;

            foreach ($properties as $property) {
                $orExpressions[] = $queryBuilder->expr()->like($property, '?' . $paramCounter);
            }

            $queryBuilder->andWhere(
                call_user_func_array(array($queryBuilder->expr(), "orX"), $orExpressions)
            );

            $queryBuilder->setParameter($paramCounter, $query);
        }

        if ($orderBy) {
            $orderByIdentifier = $this->getOrderByIdentifier($orderBy);

            if (!$sort) {
                $sort = 'ASC';
            }
            $queryBuilder->orderBy($orderByIdentifier, $sort);
        }

        // Create the paginator itself
        $paginator = new Paginator(
            new DoctrinePaginator(new ORMPaginator($queryBuilder))
        );

        $paginator->setCurrentPageNumber($page)
                  ->setItemCountPerPage($limit)
                  ->setPageRange(5);

        return $paginator;
    }
1146840
public function newEloquentBuilder($query)
    {
        return \tap(new Builder($query), function ($builder) {
            $builder->setTenantor($this->tenantor ?? null);
        });
    }
604818
public function fromQuery(Query $query, ApiResource $resource)
    {
        /** @var \Phalcon\Mvc\Model\Manager $modelsManager */
        $modelsManager = $this->di->getShared('modelsManager');

        /** @var \Phalcon\Mvc\Model\Query\Builder $builder */
        $builder = $modelsManager->createBuilder()->from($resource->getModel());

        $this->applyQuery($builder, $query, $resource);

        return $builder;
    }
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;
    }
766543
protected function addSorting(QueryBuilder $queryBuilder, array $sorting = [])
    {
        foreach ($sorting as $field => $sortOrder) {
            if (!$this->isFieldSortable($field)) {
                // Skip: invalid field
                continue;
            }
            if (!$this->isSortOrderValid($sortOrder)) {
                // Skip: invalid sort order
                continue;
            }

            $methodName = sprintf('add%sSorting', ucfirst($field));
            if (method_exists($this, $methodName)) {
                $this->$methodName($queryBuilder, $sortOrder);
                continue;
            }

            $queryBuilder->addOrderBy($this->addEntityAlias($field), strtolower($sortOrder));
        }

        return $queryBuilder;
    }
888310
public function scopeFilter($query)
    {
        if (!$this->filters) {

            $message = 'Please set the $filters property.';
            throw new FilterableSortableException($message);
        }

        $this->filters = app()->make($this->filters);

        if (!$this->filters instanceof QueryFilters) {

            $message = '$filters property must be a class instance of QueryFilter.';
            throw new FilterableSortableException($message);
        }

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

        return $query;
    }
591305
public function compileResequenceQuery(QueryBuilder $queryBuilder, ResequenceOrderIndexColumn $query) : CompiledQuery
    {
        $platform   = $queryBuilder->getConnection()->getDatabasePlatform();
        $primaryKey = $platform->quoteSingleIdentifier($query->getTable()->getPrimaryKeyColumnName());
        $table      = $platform->quoteSingleIdentifier($query->getTable()->getName());
        $column     = $platform->quoteSingleIdentifier($query->getColumn()->getName());
        $where      = $query->hasWhereCondition()
                ? $this->expressionCompiler->compileExpression($queryBuilder, $query->getWhereCondition())
                : '1=1';

        if ($query->hasGroupingColumn()) {
            $groupingColumnName = $platform->quoteSingleIdentifier($query->getGroupingColumn()->getName());

            $sql          = <<<SQL
UPDATE {$table}
SET 
    {$column} = (@__rownum:=IF({$groupingColumnName} = @__previous_group, @__rownum, 0) + 1),
	{$primaryKey} = IF((@__previous_group:={$groupingColumnName}) IS NOT NULL, {$primaryKey}, {$primaryKey})
WHERE {$where}
ORDER BY {$groupingColumnName} , {$column}, @__previous_group := NULL, @__rownum := 0
SQL;
        } else {
            $sql = <<<SQL
UPDATE {$table}
SET 
    {$column} = (@__rownum:= @__rownum + 1)
WHERE {$where}
ORDER BY {$column}, @__rownum := 0
SQL;
        }

        return new CompiledQuery($sql, $queryBuilder->getParameters());
    }
289314
protected function exportableQuery(Builder $query): Builder
    {
        // Allow executing custom exportable query.
        if (method_exists($this->module, 'exportableQuery')) {
            return $this->module->exportableQuery($query);
        }

        return $query
            ->when($query->getModel() instanceof Translatable, function ($query) {
                $query->translated();
            })
            // leave select after joining with translations
            // table in order to rewrite selected columns
            ->select($this->exportableColumns());
    }
1096030
private static function applyOptions(QueryBuilder $query, array $options)
    {
        if (isset($options['orderby'])) {
            $option = $options['orderby'];
            foreach ($option as $column => $order) {
                $query = $query->orderBy($column, $order);
            }
        }

        if (isset($options['for_update']) && $options['for_update'] === true) {
            $query->forUpdate();
        } elseif (isset($options['shared_lock']) && $options['shared_lock'] === true) {
            $query->sharedLock();
        }

        $limit  = $options['limit'] ?? null;
        $offset = $options['offset'] ?? 0;

        if ($limit !== null) {
            $query = $query->limit($limit, $offset);
        }

        return $query;
    }
647158
final public function handle(Query $query): DTO
    {
        $supportedQueryType = $this->getSupportedQueryType();
        if (!\is_a($query, $supportedQueryType)) {
            throw new InvalidQueryException(\sprintf(
                'Query command must be a %s, %s given',
                $supportedQueryType,
                \get_class($query)
            ));
        }

        return $this->handleQuery($query);
    }