Creates a all items generator.

@param Builder $query
@param int $count

@return Generator
11786
protected function each(Builder $query, $count = 100): Generator
    {
        $query = $this->exportableQuery($query);

        // enforce order by statement.
        if (empty($query->orders) && empty($query->unionOrders)) {
            $query->orderBy($query->getModel()->getQualifiedKeyName(), 'asc');
        }

        $page = 1;

        do {
            // We'll execute the query for the given page and get the results. If there are
            // no results we can just break and return from here. When there are results
            // we will call the callback with the current chunk of these results here.
            $results = $query->forPage($page, $count)->get();

            $countResults = $results->count();

            if (0 === $countResults) {
                break;
            }

            // On each chunk result set, we will pass them to the callback and then let the
            // developer take care of everything within the callback, which allows us to
            // keep the memory low for spinning through large result sets for working.
            foreach ($results as $index => $item) {
                yield $index = $item;
            }

            unset($results);

            ++$page;
        } while ($countResults === $count);
    }
1370072
protected function compileComponents(Builder $query)
    {
        if($query->orders === null) {
            $query->orderByRaw('1 asc');
        }

        $sql = parent::compileComponents($query);

        return $sql;
    }
1175587
public function scopeSearch(Builder $query, array $search = [])
    {
        if (empty($search)) {
            return $query;
        }

        if (!array_intersect(array_keys($search), $this->searchable)) {
            return $query;
        }

        return $query->where($search);
    }
109497
private function generateCustomers($count)
    {
        $customers = [];

        for ($i = 0; $i < $count; ++$i) {
            /** @var CustomerInterface $customer */
            $customer = $this->customerFactory->createNew();
            $customer->setEmail(sprintf('john%s@doe.com', uniqid()));
            $customer->setFirstname('John');
            $customer->setLastname('Doe' . $i);

            $customers[] = $customer;

            $this->customerRepository->add($customer);
        }

        return $customers;
    }
46970
public function getRelationCountQueryForSelfRelation(Builder $query, Builder $parent)
	{
		$query->select(new Expression('count(*)'));

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

		$key = $this->wrap($this->getQualifiedForeignKey());

		return $query->where($hash.'.'.$query->getModel()->getKeyName(), '=', new Expression($key));
	}
649148
public static function aggregate($query)
    {
        $rows = self::connection()->aggregate(self::collectionName(), $query);
        return $rows;
    }
1166503
private function filter(Builder $query): Builder
    {
        $filters = $this->entity->getFilters();

        foreach ($filters as $filter) {
            $query = $filter->filter($query);
        }

        return $query;
    }
375356
public function items($count = false)
    {
        $this->query = $this->model->newQuery();

        return $this->query($count);
    }
1332824
public static function create($query)
    {
        switch (true) {
            case $query instanceof self:
                return $query;
            case $query instanceof AbstractQuery:
                return new self($query);
            case empty($query):
                return new self(new MatchAll());
            case \is_array($query):
                return new self($query);
            case \is_string($query):
                return new self(new QueryString($query));
            case $query instanceof AbstractSuggest:
                return new self(new Suggest($query));

            case $query instanceof Suggest:
                return new self($query);
        }

        throw new InvalidException('Unexpected argument to create a query for.');
    }
689770
public @NotNull QueryBuilder appendPlaceholders(int count) {
        if (count <= 0) throw new IllegalArgumentException("count must be positive, but was: " + count);

        query.append('?');
        for (int i = 1; i < count; i++)
            query.append(",?");

        return this;
    }

    /**
     * Adds placeholders for all elements of collection and then adds then values
     * of collection itself.
     */
    public @NotNull QueryBuilder appendPlaceholders(@NotNull Collection<?> args) {
        appendPlaceholders(args.size());
        addArguments(args);

        return this;
    }

    /**
     * Is the query string empty?
     */
    public boolean isEmpty() {
       return query.length() == 0;
    }

    /**
     * Does this query have any arguments?
     */
    public boolean hasArguments() {
        return !arguments.isEmpty();
    }

    /**
     * Adds an argument to this query.
     */
    public @NotNull QueryBuilder addArgument(@Nullable Object argument) {
        arguments.add(argument);
        return this;
    }

    /**
     * Adds given arguments to this query.
     */
    public @NotNull QueryBuilder addArguments(Object... args) {
        return addArguments(asList(args));
    }

    /**
     * Adds given arguments to this query.
     */
    public @NotNull QueryBuilder addArguments(@NotNull Collection<?> args) {
        arguments.addAll(args);
        return this;
    }

    /**
     * Builds an SQL query from the current state of this builder.
     *
     * @throws IllegalStateException if the builder is empty
     */
    public @NotNull SqlQuery build() {
        if (query.length() == 0)
            throw new IllegalStateException("empty query");

        return SqlQuery.query(query.toString(), new ArrayList<>(arguments));
    }
}
790017
public function build($count = false)
    {
        $modelNameSpace = $this->model->getModelNameSpace();
        $mm = $this->getDI()->get('modelsManager');
        $query = $mm->createBuilder()->from($modelNameSpace);

        // $columns = $this->model->getAllowedColumns(true);
        $columns = array(
            "$modelNameSpace.*"
        );

        // process hasOne Joins
        $this->queryJoinHelper($query);
        $this->querySearchHelper($query);
        $this->querySortHelper($query);

        if ($count) {
            $query->columns('count(*) as count');
        } else {
            // preserve any columns added through joins
            $existingColumns = $query->getColumns();
            $allColumns = array_merge($columns, $existingColumns);
            $query->columns($allColumns);
        }
        // skip limit if returning a count
        if (!$count) {
            $this->queryLimitHelper($query);
        }

        // todo build fields feature into PHQL instead of doing in PHP
        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;
    }
887594
protected function makeJoins(Builder $query)
    {
        foreach ($this->getJoins() as $table => $keys) {
            $query->leftJoin($table, function ($join) use ($keys) {
                $join->on($keys[0], '=', $keys[1]);
                if (array_key_exists(2, $keys) && array_key_exists(3, $keys)) {
                    $join->whereRaw($keys[2] . ' = "' . $keys[3] . '"');
                }
            });
        }
    }
428957
public function buildQuery($query)
	{
		foreach($this->children as $child)
		{
			if($child->master!==null)
				$child->_joined=true;
			elseif($child->relation instanceof CHasOneRelation || $child->relation instanceof CBelongsToRelation
				|| $this->_finder->joinAll || $child->relation->together || (!$this->_finder->baseLimited && $child->relation->together===null))
			{
				$child->_joined=true;
				$query->join($child);
				$child->buildQuery($query);
			}
		}
	}
1046039
public function compileInsert(Builder $query, array $values)
    {
        /**
         *  Essentially we will force every insert to be treated as a batch insert which
         * simply makes creating the Cypher easier for us since we can utilize the same
         * basic routine regardless of an amount of records given to us to insert.
         *
         * We are working on getting a Cypher like this:
         * CREATE (:Wiz {fiz: 'foo', biz: 'boo'}). (:Wiz {fiz: 'morefoo', biz: 'moreboo'})
         */

        if ( ! is_array($query->from))
        {
            $query->from = array($query->from);
        }

        $label = $this->prepareLabels($query->from);

        if ( ! is_array(reset($values)))
        {
            $values = array($values);
        }

        // Prepare the values to be sent into the entities factory as
        // ['label' => ':Wiz', 'bindings' => ['fiz' => 'foo', 'biz' => 'boo']]
        $values = array_map(function($entity) use($label)
        {
            return ['label' => $label, 'bindings' => $entity];
        }, $values);
        // We need to build a list of parameter place-holders of values that are bound to the query.
        return "CREATE ". $this->prepareEntities($values);
    }
486977
public final function findAll($query = null, array $queryParams = null, $limit = null): EntityCollection
    {
        $queryBuilder = new QueryBuilder($this->db->getLink());
        $queryBuilder->setTable($this->table);

        $queryBuilder->select("{$this->table}.*");

        if (method_exists($this, 'onFind')) {
            $queryBuilder = $this->onFind($queryBuilder);
            if (!$queryBuilder || !($queryBuilder instanceof QueryBuilder)) {
                throw new InvalidValueException('You should return query builder back from onFind()!');
            }
        }

        $isEmptyQuery = empty($query);
        $isEmptyQueryParams = empty($queryParams);

        // fetch all rows, oh ohh..
        // e.g: findAll()
        if ($isEmptyQuery) {
            // nothing to do..
        }
        // fetch all rows by primary key with given params
        // e.g: findAll([1,2,3])
        elseif (!$isEmptyQuery && $isEmptyQueryParams) {
            $queryBuilder->where("{$this->table}.{$this->tablePrimary} IN(?)", [$query]);
        }
        // fetch all rows with given params and params
        // e.g: findAll('id IN (?)', [[1,2,3]])
        // e.g: findAll('id IN (?,?,?)', [1,2,3])
        elseif (!$isEmptyQuery && !$isEmptyQueryParams) {
            // now, it is user's responsibility to append table(s) before field(s)
            $queryBuilder->where($query, $queryParams);
        }

        @ [$limitStart, $limitStop] = (array) $limit;
        if ($limitStart !== null) {
            $queryBuilder->limit((int) $limitStart, $limitStop);
        }

        $hasOnEntity = method_exists($this, 'onEntity');

        $entityCollection = new EntityCollection();
        foreach ($queryBuilder->run() as $result) {
            $entity = new Entity($this, (array) $result);
            if ($hasOnEntity) {
                $this->onEntity($entity);
            }
            $entityCollection->addEntity($entity);
        }

        return $entityCollection;
    }
521993
public function scopeRecentlyCreated(Builder $query, $limit = null)
    {
        $query->orderBy('created_at', 'desc');

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

        return $query;
    }