apply all stuff from the rql query (if any) to the local querybuilder

@return void
331437
private function applyRqlQuery()
    {
        $rqlQuery = $this->getRqlQuery();

        // Setting RQL Query
        if ($rqlQuery) {
            // Check if search and if this Repository have search indexes.
            if ($query = $rqlQuery->getQuery()) {
                if ($query instanceof AndNode) {
                    foreach ($query->getQueries() as $xq) {
                        if ($xq instanceof SearchNode && !$this->hasSearchIndex()) {
                            throw new \InvalidArgumentException('Search operation not supported on this endpoint');
                        }
                    }
                } elseif ($query instanceof SearchNode && !$this->hasSearchIndex()) {
                    throw new \InvalidArgumentException('Search operation not supported on this endpoint');
                }
            }

            $this->visitor->setRepository($this->repository);
            $this->queryBuilder = $this->visitor->visit($rqlQuery);
        }

        if (is_null($this->getDocumentId()) && $this->queryBuilder instanceof Builder) {

            /*** default sort ***/
            if (!array_key_exists('sort', $this->queryBuilder->getQuery()->getQuery())) {
                $this->queryBuilder->sort('_id');
            }

            /*** pagination stuff ***/
            if (!array_key_exists('limit', $this->queryBuilder->getQuery()->getQuery())) {
                $this->queryBuilder->skip($this->getPaginationSkip());
                $this->queryBuilder->limit($this->getPaginationPageSize());
            }
        }
    }
1147701
def apply_scopes(self):
        
        if not self._scopes:
            return self

        builder = copy.copy(self)

        query = builder.get_query()

        # We will keep track of how many wheres are on the query before running the
        # scope so that we can properly group the added scope constraints in the
        # query as their own isolated nested where statement and avoid issues.
        original_where_count = len(query.wheres)

        where_counts = [0, original_where_count]

        for scope in self._scopes.values():
            self._apply_scope(scope, builder)

            # Again, we will keep track of the count each time we add where clauses so that
            # we will properly isolate each set of scope constraints inside of their own
            # nested where clause to avoid any conflicts or issues with logical order.
            where_counts.append(len(query.wheres))

        if self._should_nest_wheres_for_scope(query, original_where_count):
            self._nest_wheres_for_scope(query, Collection(where_counts).unique().all())

        return builder
329713
public function execute()
    {
        $this->query("ALTER TABLE `{{NAILS_DB_PREFIX}}blog_post` ADD `commentsEnabled` TINYINT(1)  UNSIGNED  NOT NULL  DEFAULT '1'  AFTER `seo_keywords`;");
        $this->query("ALTER TABLE `{{NAILS_DB_PREFIX}}blog_post` ADD `commentsExpire` DATETIME  NULL  AFTER `commentsEnabled`;");
        $this->query("ALTER TABLE `{{NAILS_DB_PREFIX}}blog_post` ADD `type` ENUM('TEXT','AUDIO','VIDEO','PHOTO')  NOT NULL  DEFAULT 'PHOTO'  AFTER `slug`;");
        $this->query("ALTER TABLE `{{NAILS_DB_PREFIX}}blog_post` ADD `video_url` VARCHAR(255)  NULL  DEFAULT NULL  AFTER `image_id`;");
        $this->query("ALTER TABLE `{{NAILS_DB_PREFIX}}blog_post` ADD `audio_url` VARCHAR(255)  NULL  DEFAULT NULL  AFTER `video_url`;");
        $this->query("UPDATE `{{NAILS_DB_PREFIX}}blog_post` SET type = 'TEXT' WHERE image_id IS NULL;");
    }
240014
public function apply(Builder $query)
    {
        $this->specificationSet->applyAll($query);
        $this->sortingSet->applyAll($query);
        $this->paramSet->apply($query);
    }
308893
public function prepareQuery()
    {
        $query = $this->model->newQuery();
        $primaryTable = $this->model->getTable();
        $selects = [$primaryTable.'.*'];
        $joins = [];
        $withs = [];

        /**
         * @event backend.list.extendQueryBefore
         * Provides an opportunity to modify the `$query` object before the List widget applies its scopes to it.
         *
         * Example usage:
         *
         *     Event::listen('backend.list.extendQueryBefore', function($listWidget, $query) {
         *         $query->whereNull('deleted_at');
         *     });
         *
         * Or
         *
         *     $listWidget->bindEvent('list.extendQueryBefore', function ($query) {
         *         $query->whereNull('deleted_at');
         *     });
         *
         */
        $this->fireSystemEvent('backend.list.extendQueryBefore', [$query]);

        /*
         * Prepare searchable column names
         */
        $primarySearchable = [];
        $relationSearchable = [];

        $columnsToSearch = [];
        if (!empty($this->searchTerm) && ($searchableColumns = $this->getSearchableColumns())) {
            foreach ($searchableColumns as $column) {
                /*
                 * Related
                 */
                if ($this->isColumnRelated($column)) {
                    $table = $this->model->makeRelation($column->relation)->getTable();
                    $columnName = isset($column->sqlSelect)
                        ? DbDongle::raw($this->parseTableName($column->sqlSelect, $table))
                        : $table . '.' . $column->valueFrom;

                    $relationSearchable[$column->relation][] = $columnName;
                }
                /*
                 * Primary
                 */
                else {
                    $columnName = isset($column->sqlSelect)
                        ? DbDongle::raw($this->parseTableName($column->sqlSelect, $primaryTable))
                        : DbDongle::cast(Db::getTablePrefix() . $primaryTable . '.' . $column->columnName, 'TEXT');

                    $primarySearchable[] = $columnName;
                }
            }
        }

        /*
         * Prepare related eager loads (withs) and custom selects (joins)
         */
        foreach ($this->getVisibleColumns() as $column) {

            // If useRelationCount is enabled, eager load the count of the relation into $relation_count
            if ($column->relation && @$column->config['useRelationCount']) {
                $query->withCount($column->relation);
            }

            if (!$this->isColumnRelated($column) || (!isset($column->sqlSelect) && !isset($column->valueFrom))) {
                continue;
            }

            if (isset($column->valueFrom)) {
                $withs[] = $column->relation;
            }

            $joins[] = $column->relation;
        }

        /*
         * Add eager loads to the query
         */
        if ($withs) {
            $query->with(array_unique($withs));
        }

        /*
         * Apply search term
         */
        $query->where(function ($innerQuery) use ($primarySearchable, $relationSearchable, $joins) {

            /*
             * Search primary columns
             */
            if (count($primarySearchable) > 0) {
                $this->applySearchToQuery($innerQuery, $primarySearchable, 'or');
            }

            /*
             * Search relation columns
             */
            if ($joins) {
                foreach (array_unique($joins) as $join) {
                    /*
                     * Apply a supplied search term for relation columns and
                     * constrain the query only if there is something to search for
                     */
                    $columnsToSearch = array_get($relationSearchable, $join, []);

                    if (count($columnsToSearch) > 0) {
                        $innerQuery->orWhereHas($join, function ($_query) use ($columnsToSearch) {
                            $this->applySearchToQuery($_query, $columnsToSearch);
                        });
                    }
                }
            }

        });

        /*
         * Custom select queries
         */
        foreach ($this->getVisibleColumns() as $column) {
            if (!isset($column->sqlSelect)) {
                continue;
            }

            $alias = $query->getQuery()->getGrammar()->wrap($column->columnName);

            /*
             * Relation column
             */
            if (isset($column->relation)) {

                // @todo Find a way...
                $relationType = $this->model->getRelationType($column->relation);
                if ($relationType == 'morphTo') {
                    throw new ApplicationException('The relationship morphTo is not supported for list columns.');
                }

                $table =  $this->model->makeRelation($column->relation)->getTable();
                $sqlSelect = $this->parseTableName($column->sqlSelect, $table);

                /*
                 * Manipulate a count query for the sub query
                 */
                $relationObj = $this->model->{$column->relation}();
                $countQuery = $relationObj->getRelationExistenceQuery($relationObj->getRelated()->newQueryWithoutScopes(), $query);

                $joinSql = $this->isColumnRelated($column, true)
                    ? DbDongle::raw("group_concat(" . $sqlSelect . " separator ', ')")
                    : DbDongle::raw($sqlSelect);

                $joinSql = $countQuery->select($joinSql)->toSql();

                $selects[] = Db::raw("(".$joinSql.") as ".$alias);
            }
            /*
             * Primary column
             */
            else {
                $sqlSelect = $this->parseTableName($column->sqlSelect, $primaryTable);
                $selects[] = DbDongle::raw($sqlSelect . ' as '. $alias);
            }
        }

        /*
         * Apply sorting
         */
        if (($sortColumn = $this->getSortColumn()) && !$this->showTree) {
            if (($column = array_get($this->allColumns, $sortColumn)) && $column->valueFrom) {
                $sortColumn = $this->isColumnPivot($column)
                    ? 'pivot_' . $column->valueFrom
                    : $column->valueFrom;
            }

            // Set the sorting column to $relation_count if useRelationCount enabled
            if (isset($column->relation) && @$column->config['useRelationCount']) {
                $sortColumn = $column->relation . '_count';
            }

            $query->orderBy($sortColumn, $this->sortDirection);
        }

        /*
         * Apply filters
         */
        foreach ($this->filterCallbacks as $callback) {
            $callback($query);
        }

        /*
         * Add custom selects
         */
        $query->addSelect($selects);

        /**
         * @event backend.list.extendQuery
         * Provides an opportunity to modify and / or return the `$query` object after the List widget has applied its scopes to it and before it's used to get the records.
         *
         * Example usage:
         *
         *     Event::listen('backend.list.extendQuery', function($listWidget, $query) {
         *         $newQuery = MyModel::newQuery();
         *         return $newQuery;
         *     });
         *
         * Or
         *
         *     $listWidget->bindEvent('list.extendQuery', function ($query) {
         *         $query->whereNull('deleted_at');
         *     });
         *
         */
        if ($event = $this->fireSystemEvent('backend.list.extendQuery', [$query])) {
            return $event;
        }

        return $query;
    }
607749
protected function baseQuery()
    {
        if (empty($this->baseQuery) && $this->parent->getData()) {
            $pk = $this->parent->getPk();

            $this->query->where([
                [$this->morphKey, '=', $this->parent->$pk],
                [$this->morphType, '=', $this->type],
            ]);
            $this->baseQuery = true;
        }
    }
1351052
protected function executeCallbacks()
	{
		if ($this->callbacks_executed) {
			return;
		}
		
		$this->callbacks_executed = true;
		
		foreach ($this->callbacks as $callback) {
			if ($q = call_user_func($callback, $this->query)) {
				$this->query = $q;
			}
		}
	}
886576
protected function setSearchCriteriaFromQuery()
    {
        $this->initSearchCriteria();

        foreach ($this->aCriteria as $sIndex => $mValue) {
            $this->aCriteria[$sIndex] = $this->app['request']->query->get($sIndex, $mValue);
        }
    }
913180
private function assembleQuery()
    {
        $this->assembleWheres();

        $this->assembleOrWheres();

        /*
         * Make sure we wrap the query in an 'and'
         * if using multiple wheres or if we have any
         * orWheres. For example (&(cn=John*)(|(description=User*)))
         */
        if (count($this->getWheres()) > 1 || count($this->getOrWheres()) > 0) {
            $this->setQuery($this->buildAnd($this->getQuery()));
        }
    }
1028809
private function compileQuery()
    {
        if ($this->queryConfiguration->isGlobalSearch()) {
            $this->compileGlobalQuery();
        } elseif ($this->queryConfiguration->isColumnSearch()) {
            $this->compileColumnQuery();
        }
    }
898263
public function clear(): void
    {
        $queryBuilder = $this->entityManager->createQueryBuilder();
        $queryBuilder->delete(CachedSearchResult::class, 'r');

        $queryBuilder->getQuery()->execute();
    }
528195
public function applyFilters()
    {
        if ($this->filters) {
            foreach ($this->filters as $k => $filter) {
                if (
                    isset($_GET[$filter['field']]) &&
                    !empty($_GET[$filter['field']]) &&
                    $_GET[$filter['field']] != $this->filterEmpty &&
                    @$_GET['filter'] != $filter['field']
                ) {
                    $this->model->addCondition($filter['field'], $_GET[$filter['field']]);
                }
            }
        }
    }
385206
public function buildQuery($query)
    {
        $q = $this->request->getQuery();

        foreach ($query as $key => $value)
        {
            $q[$key] = $value;
        }
    }
1142936
protected function execPre()
    {
        foreach ($this->preQueries as $pq) {
            if (is_array($pq)) {
                $pattern = $pq[0];
                $data = isset($pq[1]) ? $pq[1] : null;
            } else {
                $pattern = $pq;
                $data = null;
            }
            $this->query($pattern, $data);
        }
        $this->preQueries = array();
    }
1331490
protected function quickSearch()
    {
        if ($this->getQuickSearchQuery()) {
            $where = $this->getQuickSearchQuery()->getRawState('where');
            $this->select->where($where);
        }
    }
1160460
public function initActiveQuery()
    {
        $this->activeQuery = Tree::find();

        if ($this->treePid) {
            $this->activeQuery->andWhere(['pid' => $this->treePid]);
        }

        if ($this->level) {
            $this->activeQuery->andWhere(['level' => $this->level]);
        }

        if ($this->active) {
            $this->activeQuery->andWhere(['active' => $this->active]);
        }

        if ($this->site_codes) {
            $cmsSites = CmsSite::find()->where(['code' => $this->site_codes])->all();
            if ($cmsSites) {
                $ids = ArrayHelper::map($cmsSites, 'id', 'id');
                $this->activeQuery->andWhere(['cms_site_id' => $ids]);
            }
        }

        if ($this->enabledCurrentSite == Cms::BOOL_Y && \Yii::$app->cms->site) {
            $this->activeQuery->andWhere(['cms_site_id' => \Yii::$app->cms->site->id]);
        }

        if ($this->orderBy) {
            $this->activeQuery->orderBy([$this->orderBy => (int)$this->order]);
        }

        if ($this->tree_type_ids) {
            $this->activeQuery->andWhere(['tree_type_id' => $this->tree_type_ids]);
        }


        if ($this->with) {
            $this->activeQuery->with($this->with);
        }

        if ($this->activeQueryCallback && is_callable($this->activeQueryCallback)) {
            $callback = $this->activeQueryCallback;
            $callback($this->activeQuery);
        }

        return $this;
    }
26228
public function apply($builder, QueryInterface $query): void
    {
        // Apply joins
        foreach ($query->getJoins() as $join) {
            if ($join->isInner()) {
                $builder->innerJoin($join->getFromAlias(), $join->getTo(), $join->getToAlias(), $join->getCondition());
            } else {
                $builder->leftJoin($join->getFromAlias(), $join->getTo(), $join->getToAlias(), $join->getCondition());
            }
        }

        // Apply rules
        foreach ($query->getRules() as $rule) {
            $builder->andWhere($rule->getRule());
        }

        // Apply parameters
        foreach ($query->getParameters() as $parameter) {
            $builder->setParameter($parameter->getName(), $parameter->getValue(), $parameter->getType());
        }

        // Apply orders
        foreach ($query->getOrders() as $order) {
            $builder->addOrderBy($order->getField(), $order->getDirection());
        }
    }