Process multiple query results and return model instances.

@param \Anax\Database\DatabaseQueryBuilder   $query  Database service instance with executed internal query.

@return array                                        Array of model instances.
510540
protected function processMultipleResults($query)
    {
        if (!empty($this->fetchRefs)) {
            $models = [];
            foreach ($query->fetchAll() as $model) {
                $models[] = $this->populateModelFromJoin($model);
            }
        } else {
            $models = $query->fetchAllClass($this->modelClass);
        }
        if (isset($this->manager)) {
            foreach ($models as $model) {
                $this->manager->manageModel($model);
            }
        }
        $this->fetchReferences(false);
        return $models;
    }
435258
protected function compileComponents(Builder $query)
    {
        $sql = [];

        foreach ($this->selectComponents as $component) {
            // To compile the query, we'll spin through each component of the query and
            // see if that component exists. If it does we'll just call the compiler
            // function for the component which is responsible for making the SQL.
            if (isset($query->$component) && ! is_null($query->$component)) {
                $method = 'compile'.ucfirst($component);

                $sql[$component] = $this->$method($query, $query->$component);
            }
        }

        return $sql;
    }
244307
public function all(Query $query = null) {
		$query = Query::forge($query);
		$collection = parent::all($query);
		if(YII_ENV_TEST) {
			$collection[] = $this->forgeEntity([
				'title' => 'Source',
				'name' => 'source',
				'code' => LanguageEnum::code(LanguageEnum::SOURCE),
				'locale' => LanguageEnum::SOURCE,
				'is_main' => false,
				'is_enabled' => true,
			]);
		}
		return $collection;
	}
1166503
private function filter(Builder $query): Builder
    {
        $filters = $this->entity->getFilters();

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

        return $query;
    }
1229904
public function compileExists(Builder $query)
    {
        $q          = clone $query;
        $q->columns = [];
        $q->selectRaw('1 as "exists"')
          ->whereRaw('rownum = 1');

        return $this->compileSelect($q);
    }
727476
protected function load(QueryBuilder $query)
    {
        $metadata = $this->getClassMetadata();
        foreach ($metadata->getFieldMappings() as $field) {
            $fieldtype = $this->getFieldManager()->get($field['fieldtype'], $field);
            if ($fieldtype instanceof FieldTypeInterface) {
                $fieldtype->load($query, $metadata);
            }
        }
    }
940666
protected function execute($query)
    {
        $query->execute($this->bindings);
        
        $this->bindings = [];
        $this->wheres   = [];

        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;
    }
310950
public function scopeClients(Builder $query)
    {
        $query->with('roles')->whereNotNull('tbl_users.id')->whereHas('roles', function ($query) {
            $query->whereIn('tbl_roles.name', ['member', 'users', 'user']);
        });


        return $query;
    }
1093848
public function queryJoinHelper(BuilderInterface $query)
    {
        $config = $this->getDI()->get('config');
        $modelNameSpace = $config['namespaces']['models'];

        $columns = [];
        // join all active hasOne and belongTo instead of just the parent hasOne
        foreach ($this->entity->activeRelations as $relation) {

            // be sure to skip any relationships that are marked for custom processing
            $relationOptions = $relation->getOptions();
            if (isset($relationOptions) && (array_key_exists('customProcessing',
                        $relationOptions) && ($relationOptions['customProcessing'] === true))
            ) {
                continue;
            }

            // refer to alias or model path to prefix each relationship
            // prefer alias over model path in case of collisions
            $alias = $relation->getAlias();
            $referencedModel = $relation->getReferencedModel();
            if (!$alias) {
                $alias = $referencedModel;
            }

            $type = $relation->getType();
            switch ($type) {
                // structure to always join in belongsTo just in case the query filters by a related field
                case Relation::BELONGS_TO:
                    // create both sides of the join
                    $left = "[$alias]." . $relation->getReferencedFields();
                    $right = $modelNameSpace . $this->model->getModelName() . '.' . $relation->getFields();
                    // create and alias join
                    $query->leftJoin($referencedModel, "$left = $right", $alias);
                    break;

                case Relation::HAS_ONE:
                    // create both sides of the join
                    $left = "[$alias]." . $relation->getReferencedFields();
                    $right = $modelNameSpace . $this->model->getModelName() . '.' . $relation->getFields();
                    // create and alias join
                    $query->leftJoin($referencedModel, "$left = $right", $alias);

                    // add all parent AND hasOne joins to the column list
                    $columns[] = "[$alias].*";
                    break;

                // stop processing these types of joins with the main query.  They might return "n" number of related records
//                case Relation::HAS_MANY_THROUGH:
//                    $alias2 = $alias . '_intermediate';
//                    $left1 = $modelNameSpace . $this->model->getModelName() . '.' . $relation->getFields();
//                    $right1 = "[$alias2]." . $relation->getIntermediateFields();
//                    $query->leftJoin($relation->getIntermediateModel(), "$left1 = $right1", $alias2);
//
//                    $left2 = "[$alias2]." . $relation->getIntermediateReferencedFields();
//                    $right2 = "[$alias]." . $relation->getReferencedFields();
//                    $query->leftJoin($referencedModel, "$left2 = $right2", $alias);
//                    break;

                default:
                    $this->di->get('logger')->warning("Relationship was ignored during join: {$this->model->getModelName()}.$alias, type #$type");
            }

            // attempt to join in side loaded belongsTo records
            // add all parent AND hasOne joins to the column list
            if ($type == Relation::BELONGS_TO) {
                $columns[] = "[$alias].*";
            }
        }
        $query->columns($columns);
        return $query;
    }
1169731
public function findAllByQuery($query, array $params = array()) {
		//Not using the parent findAllByQuery() implementation, becaus
		//it performs one-by-one EAV fetching, which is very bad for performance.
		//Instead, we find all main records with 1 query. And then fine all EAV entries (for all),
		//with a single additional query (instead of one per main record).

		$records = array();
		$recordIds = array();
		foreach ($this->db->fetchAll($query, $params) as $data) {
			$records[] = $data;
			$recordIds[] = $data['_id'];
		}

		$dataPerNamespaceFlattened = $this->pullEavDataForAll($recordIds);

		$results = array();
		foreach ($records as $data) {
			$data['__eav_data__'] = $dataPerNamespaceFlattened[$data['_id']];
			$results[] = $this->loadModel($data);
		}

		return $results;
	}
1205010
final public function queryArrayOne(string $query, string $field = '')
    {
        $result = $this->queryResult($query);
        if (false === $result) {
            return false;
        }

        $return = [];
        $verifiedFieldName = false;
        while ($row = $result->fetchRow()) {
            if ('' === $field) {
                $keys = array_keys($row);
                $field = $keys[0];
                $verifiedFieldName = true;
            }
            if (! $verifiedFieldName) {
                if (! array_key_exists($field, $row)) {
                    return false;
                }
                $verifiedFieldName = true;
            }
            $return[] = $row[$field] ?? null;
        }
        return $return;
    }
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());
    }
380954
public function prepareQueryOrNewObj(array $query)
    {
        $preparedQuery = array();

        foreach ($query as $key => $value) {
            // Recursively prepare logical query clauses
            if (in_array($key, array('$and', '$or', '$nor')) && is_array($value)) {
                foreach ($value as $k2 => $v2) {
                    $preparedQuery[$key][$k2] = $this->prepareQueryOrNewObj($v2);
                }
                continue;
            }

            if (isset($key[0]) && $key[0] === '$' && is_array($value)) {
                $preparedQuery[$key] = $this->prepareQueryOrNewObj($value);
                continue;
            }

            list($key, $value) = $this->prepareQueryElement($key, $value, null, true);

            $preparedQuery[$key] = is_array($value)
                ? array_map('Doctrine\ODM\MongoDB\Types\Type::convertPHPToDatabaseValue', $value)
                : Type::convertPHPToDatabaseValue($value);
        }

        return $preparedQuery;
    }
271716
public function query(WorkflowExpressionQuery $query)
    {
        $results = [];

        foreach (static::$entryCache as $entryId => $mapEntry) {
            if ($this->queryInternal($entryId, $query)) {
                $results[$entryId] = $entryId;
            }
        }

        return $results;
    }
191190
public function rules($query = null)
    {
        $model = $this->model;

        // get rules from the model if set
        if (isset($model::$rules)) {
            $rules = $model::$rules;
        } else {
            $rules = [];
        }

        // if the there are no rules
        if (!is_array($rules) || !$rules) {
            // return an empty array
            return [];
        }

        // if the query is empty
        if (!$query) {
            // return all of the rules
            return array_filter($rules);
        }

        // return the relevant rules
        return array_filter(array_only($rules, $query));
    }
786535
private function getBuilder($query)
    {
        $queryType = $query->getType();

        if (!isset($this->builders[$queryType])) {
            throw new \InvalidArgumentException("Unknow query builder for {$queryType}.");
        }

        return $this->builders[$queryType];
    }