Advanced search from query builder.

@param  \Illuminate\Database\Query\Builder $query
@param  string|null  $search
@param  array|null  $columns

@return \Illuminate\Database\Query\Builder
553900
public function scopeAdvancedSearch(Builder $query, ?string $search, ?array $columns = null): Builder
    {
        ['basic' => $basic, 'advanced' => $advanced] = $this->resolveSearchKeywords($search ?? '');
        $rules = $this->getSearchableRules();
        $others = [];

        foreach ($rules as $keyword => $callback) {
            if (Str::contains($keyword, ':*') || Str::contains($keyword, ':[]')) {
                [$tag, $type] = \explode(':', $keyword, 2);

                $results = Arr::where($advanced, function ($value) use ($tag) {
                    return Str::startsWith($value, "{$tag}:");
                });

                $query->unless(empty($results), function ($query) use ($callback, $results, $type) {
                    if ($type === '*') {
                        [, $value] = \explode(':', $results[0] ?? null, 2);
                        $value = \trim($value, '"');
                    } else {
                        $value = \array_map(function ($text) {
                            [, $value] = \explode(':', $text, 2);

                            return \trim($value, '"');
                        }, $results);
                    }

                    \call_user_func($callback, $query, $value);

                    return $query;
                });
            } else {
                $query->when(\in_array($keyword, $advanced), function ($query) use ($callback) {
                    \call_user_func($callback, $query);

                    return $query;
                });
            }
        }

        if (\is_null($columns) && \method_exists($this, 'getSearchableColumns')) {
            $columns = $this->getSearchableColumns();
        }

        return $this->setupWildcardQueryFilter($query, $basic, $columns ?? []);
    }
846557
public function getRelationExistenceQuery(Builder $query, Builder $parentQuery, $columns = ['*'])
    {
        if ($parentQuery->getQuery()->from == $query->getQuery()->from) {
            return $this->getRelationExistenceQueryForSelfRelation($query, $parentQuery, $columns);
        }

        return $query->select($columns)->whereColumn(
            $this->getQualifiedForeignKeyName(), '=', $query->qualifyColumn($this->ownerKey)
        );
    }
1325646
public function getRelationExistenceQueryForSelfJoin(Builder $query, Builder $parentQuery, $columns = ['*'])
    {
        $query->select($columns);

        $query->from($this->related->getTable().' as '.$hash = $this->getRelationCountHash());

        $this->related->setTable($hash);

        $this->performJoin($query);

        return parent::getRelationExistenceQuery($query, $parentQuery, $columns);
    }
596885
public function getRelationQuery(Builder $query, Builder $parent, $columns = ['*'])
	{
		if ($parent->getQuery()->from == $query->getQuery()->from) {
			return $this->getRelationQueryForSelfRelation($query, $parent, $columns);
		}

		return parent::getRelationQuery($query, $parent, $columns);
	}
477350
public function queryResultC($query, $params, $row, $col)
    {
        trigger_error('queryResultC() is deprecated in favour of method chaining, eg $sql->cache($query, $params)->result(0, 0)', E_USER_DEPRECATED);
        return $this->cache($query, $params)->result($row, $col);
    }
1341173
public function getRelationExistenceQuery(Builder $query, Builder $parentQuery, $columns = ['*'])
    {
        if ($parentQuery->getQuery()->from === $query->getQuery()->from) {
            return $this->getRelationExistenceQueryForSelfRelation($query, $parentQuery, $columns);
        }

        if ($parentQuery->getQuery()->from === $this->throughParent->getTable()) {
            return $this->getRelationExistenceQueryForThroughSelfRelation($query, $parentQuery, $columns);
        }

        $this->performJoin($query);

        return $query->select($columns)->whereColumn(
            $this->getQualifiedLocalKeyName(), '=', $this->getQualifiedFirstKeyName()
        );
    }
256716
public function columnSearch()
    {
        $columns = $this->request->columns();

        foreach ($columns as $index => $column) {
            if (! $this->request->isColumnSearchable($index)) {
                continue;
            }

            $column = $this->getColumnName($index);

            if ($this->hasFilterColumn($column)) {
                $keyword = $this->getColumnSearchKeyword($index, $raw = true);
                $this->applyFilterColumn($this->getBaseQueryBuilder(), $column, $keyword);
            } else {
                $column  = $this->resolveRelationColumn($column);
                $keyword = $this->getColumnSearchKeyword($index);
                $this->compileColumnSearch($index, $column, $keyword);
            }

            $this->isFilterApplied = true;
        }
    }
360148
public function getRelationExistenceQueryForSelfRelation(Builder $query, Builder $parentQuery, $columns = ['*'])
    {
        $query->from($query->getModel()->getTable().' as '.$hash = $this->getRelationCountHash());

        $this->performJoin($query);

        $query->getModel()->setTable($hash);

        return $query->select($columns)->whereColumn(
            $parentQuery->getQuery()->from.'.'.$query->getModel()->getKeyName(), '=', $this->getQualifiedFirstKeyName()
        );
    }
347229
protected function mappedHasQuery(Builder $query, $method, ArgumentBag $args, $target, $column)
    {
        $boolean = $this->getMappedBoolean($args);

        $operator = $this->getMappedOperator($method, $args);

        $args->set('column', $column);

        return $query
            ->has($target, $operator, 1, $boolean, $this->getMappedWhereConstraint($method, $args))
            ->with($target);
    }
1025571
public function getRelationExistenceQuery(Builder $query, Builder $parentQuery, $columns = ['*'])
    {
        $query = parent::getRelationExistenceQuery($query, $parentQuery, $columns);

        if (is_array($this->foreignKeys[0])) {
            $column = $this->throughParent->qualifyColumn($this->foreignKeys[0][0]);

            $query->where($column, '=', $this->farParent->getMorphClass());
        }

        return $query;
    }
63243
private function _hasFilterExecuteForCyrillicColumn(string $search, string $column): bool
    {
        if (!preg_match("/[\w]+/i", $search) && \Assurrussa\GridView\Enums\FilterEnum::hasFilterExecuteForCyrillicColumn($column)) {
            return true;
        }

        return false;
    }
251498
public function select($columns = "*") : QueryBuilder
    {
        $this->_query[] = "SELECT";

        //Parse column(s)
        if(is_array($columns)) {
            $select_columns = "";

            $size = sizeof($columns);
            for($i = 0; $i < $size; $i++) {
                if($i > 0) {
                    $select_columns .= ', ';
                }

                $select_columns .= '`'. $this->sanitize((string)$columns[$i]) .'`';
            }

            $this->_query[] = $select_columns;

            return $this;
        }

        $select_columns = "*";
        if(
            !empty($columns) &&
            $columns !== "*"
        ) {
            $select_columns = '`'. $this->sanitize((string)$columns) .'`';
        }

        $this->_query[] = $select_columns;

        return $this;
    }
128032
protected function compileRelationSearch($query, $relation, $column, $keyword)
    {
        $myQuery = clone $this->query;
        $myQuery->orWhereHas($relation, function ($q) use ($column, $keyword, $query) {
            $sql = $q->select($this->connection->raw('count(1)'))
                    ->where($column, 'like', $keyword)
                    ->toSql();
            $sql = "($sql) >= 1";
            $query->orWhereRaw($sql, [$keyword]);
        });
    }
1093417
protected function process_query(Query $query, array $columns = [], array $defaults = [])
	{
		// Count all items
		$all_items_count = $query->count();

		// Process incoming sorting values
		$sort = [];
		for ($i = 0; $i < \Input::param('iSortingCols'); $i++)
		{
			$sort[\Input::param('iSortCol_'.$i)] = \Input::param('sSortDir_'.$i);
		}

		$i = 0;
		$order_by = [];
		$where = [];
		$global_filter = \Input::param('sSearch');

		foreach ($columns as $key => $value)
		{
			$rels = explode('.', $key);

			$rel = '';

			for ($j=0; $j < count($rels) - 1 and count($rels) > 1; $j++)
			{
				$rel .= '.' . $rels[$j];
				$query->related($rel);
			}

			$value = \Arr::merge($defaults, $value);

			if ($eav = \Arr::get($value, 'eav', false))
			{
				$query->related($rel . '.' . $eav);
			}

			// Order by statement
			if (\Input::param('bSortable_'.$i, true) and \Arr::get($value, 'sort', true) and array_key_exists($i,  $sort))
			{
				$order_by[$key] = $sort[$i];
			}

			$filter = \Input::param('sSearch_'.$i);

			$filter = json_decode($filter);

			if ( ! in_array($filter, array(null, '', 'null')) and \Input::param('bSearchable_'.$i, true) and \Arr::get($value, 'search', true))
			{
				switch (\Arr::get($value, 'type', 'text'))
				{
					case 'select-multiple':
					case 'select':
					case 'enum':
						$query->where($key, 'IN', $filter);
						break;
					case 'select-single':
					case 'number':
						$query->where($key, $filter);
						break;
					case 'text':
						$query->where($key, 'LIKE', '%' . $filter . '%');
						break;
					case 'range':
						$query->where($key, 'BETWEEN', $filter);
						break;
					default:
						break;
				}
			}

			if ( ! empty($global_filter))
			{
				if (\Arr::get($value, 'search', true) === true and \Arr::get($value, 'global', true) === true)
				{
					$where[] = array($key, 'LIKE', '%' . $global_filter . '%');
				}
			}

			$i++;
		}

		if ( ! empty($where))
		{
			$query->where_open();
			foreach ($where as $where)
			{
				$query->or_where($where[0], $where[1], $where[2]);
			}
			$query->where_close();
		}

		// Order query
		$query->order_by($order_by);

		$partial_items_count = $query->count();

		// Limit query
		$query
			->limit(\Input::param('iDisplayLength', 10))
			->offset(\Input::param('iDisplayStart', 0));

		return array($all_items_count, $partial_items_count);
	}
394481
public function selectQuery(string $prefix, array $from = [], array $columns = []): SelectQuery
    {
        return new SelectQuery($this, $this->getCompiler($prefix), $from, $columns);
    }
902904
protected static function applyRelationFilter($query, $column, $searchValue)
    {
        if ($methodName = self::hasCustomSearch(str_replace('.', '_', $column))) {
            return self::$class::$methodName($query, $searchValue);
        }

        list($relationName, $relationColumnName) = getRelationDetails($column);
        $searchValue = '%'.$searchValue.'%';

        return $query->orWhereHas($relationName, function ($query) use ($relationColumnName, $searchValue) {
            $query->where($relationColumnName, 'like', "$searchValue");
        });
    }
1023285
public function getRelationExistenceQueryForSelfRelation(Builder $query, Builder $parentQuery, $columns = ['*'])
    {
        $query->from($query->getModel()->getTable().' as '.$hash = $this->getRelationCountHash());

        $query->getModel()->setTable($hash);

        return $query->select($columns)->whereColumn(
            $this->getQualifiedParentKeyName(), '=', $hash.'.'.$this->getForeignKeyName()
        );
    }