Will apply conditions defined inside $m onto query $q.

@param Model            $m
@param \atk4\dsql\Query $q

@return \atk4\dsql\Query
9327
public function initQueryConditions($m, $q)
    {
        if (!isset($m->conditions)) {
            // no conditions are set in the model
            return $q;
        }

        foreach ($m->conditions as $cond) {

            // Options here are:
            // count($cond) == 1, we will pass the only
            // parameter inside where()

            if (count($cond) == 1) {

                // OR conditions
                if (is_array($cond[0])) {
                    foreach ($cond[0] as &$row) {
                        if (is_string($row[0])) {
                            $row[0] = $m->getField($row[0]);
                        }
                    }
                }

                $q->where($cond[0]);
                continue;
            }

            if (is_string($cond[0])) {
                $cond[0] = $m->getField($cond[0]);
            }

            if (count($cond) == 2) {
                if ($cond[0] instanceof Field) {
                    $cond[1] = $this->typecastSaveField($cond[0], $cond[1]);
                }
                $q->where($cond[0], $cond[1]);
            } else {
                if ($cond[0] instanceof Field) {
                    $cond[2] = $this->typecastSaveField($cond[0], $cond[2]);
                }
                $q->where($cond[0], $cond[1], $cond[2]);
            }
        }

        return $q;
    }
422772
private function newMetaQuery()
	{
		$meta_model = $this->metaModel();
		$meta_instance = new $meta_model;
		
		$query = $meta_instance->newQuery();
		
		if (method_exists($this, 'metaContext')) {
			if (method_exists($meta_model, 'applyQueryContext')) {
				call_user_func_array(
					array($meta_model, 'applyQueryContext'),
					array($query, $this->metaContext())
				);
			}
		}
		
		return $query;
	}
1319213
public function run(&$query, $model, $request)
    {
        $this->query = $query;
        $this->getAttributes($model);
        $this->parseRequest($request);

        return $this->query();
    }
228500
protected function search(ModelCriteria $query, Request $request)
    {
        $filters = $this->getFilters($request);

        if (empty($filters)) {
            return $query;
        }

        $conditions = array();

        $columns = $this->getSearchColumns($request);

        if (is_array($filters)) {
            foreach ($columns as $name => $condition) {
                $items = explode('.', $name);
                $i = 0;
                $values = $filters;

                while (is_array($values) && array_key_exists($items[$i], $values)) {
                    $values = $values[$items[$i]];
                    $i++;
                }

                if (is_array($values)) {
                    continue;
                } else {
                    $value = trim($values);
                }

                if (empty($value) && !is_numeric($value)) {
                    continue;
                }

                $query->condition(
                    'search_'.$name,
                    sprintf($condition, $value)
                );

                $conditions[] = 'search_'.$name;
            }

            if (!empty($conditions)) {
                return $query->where($conditions, 'and');
            }
        } else {
            $value = trim($filters);

            foreach ($columns as $name => $condition) {
                $query->condition(
                    'search_'.$name,
                    sprintf($condition, $value)
                );

                $conditions[] = 'search_'.$name;
            }

            if (!empty($conditions)) {
                return $query->where($conditions, 'or');
            }
        }
    }
268825
public function query($qs = null)
    {
        if (func_num_args() === 0) {
            return $this->_query;
        }
        if (is_string($qs)) {
            parse_str($qs, $qs);
        }
        $this->_query = $qs + $this->_query;
        return $this;
    }
869741
protected function modifyRelationQueryForContext(Model $model, $query)
    {
        /** @var Relation $relation */
        $information = $this->getInformationRepository()->getByModel($model);

        if ( ! $information) {
            return $query;
        }

        // Deal with global scopes, if any
        $disableScopes = $information->meta->disable_global_scopes;

        if (true === $disableScopes || is_array($disableScopes)) {
            $query->withoutGlobalScopes(
                true === $disableScopes ? null : $disableScopes
            );
        }

        // Apply repository context, if any
        $strategy = $information->meta->repository_strategy;

        if ($strategy) {
            $strategy = $this->resolveContextStrategy($strategy);

            if ($strategy) {
                $query = $strategy->apply($query, $information);
            }
        }

        return $query;
    }
236586
private function prepareCondition($q)
    {
        $condition = [];
        foreach ($this->searchFields as $field) {
            $condition[] = ['like', $field, $q];
        }
        if (count($this->searchFields) > 1) {
            array_unshift($condition, 'or');
        }
        return $condition;
    }
716243
function Query(model, action, conditions) {
    var self = this;
    self.model = model;
    self.action = action || 'all';
    self.q = {
        conditions: {},
        params: {},
        pkey: false,
        fields: false
    };
    if (typeof conditions === 'object') {
        self.q.conditions = helpers.merge(self.q.conditions, conditions);
    }

    ['all', 'run', 'exec'].forEach(function(method) {
        self[method] = function(params, callback) {
            if (arguments.length === 1) {
                callback = params;
                params = {};
            }
            params = buildQuery(params, this);
            var action = self.action ? self.action : 'all';
            self.model[action](params, callback);
        };
    });

    ['find', 'findOne'].forEach(function(method) {
        self[method] = function(params, callback) {
            if (arguments.length === 1) {
                callback = params;
                params = {};
            }
            params = buildQuery(params, this);
            self.model[method](params, callback);
        };
    });

    ['skip', 'limit', 'order', 'sort', 'group'].forEach(function(method) {
        self[method] = function(key, value) {
            this.q.pkey = false;
            if (method === 'sort') {
                method = 'order';
            }
            if (typeof value === 'undefined') {
                if (/^-/.test(key)) {
                    this.q.params[method] = key.replace(/^-/, '') + ' DESC';
                } else {
                    this.q.params[method] = key;
                }
            } else {
                this.q.params[method] = key + ' ' + value;
            }
            return this;
        };
    });

    self.asc = function(value) {
        this.q.pkey = false;
        this.q.params['order'] = value + ' ASC';
        return this;
    };

    self.desc = function(value) {
        this.q.pkey = false;
        this.q.params['order'] = value + ' DESC';
        return this;
    };

    self.where = function(key, value) {
        if (typeof value === 'undefined') {
            this.q.pkey = key;
        } else {
            this.q.pkey = false;
            this.q.conditions[key] = value;
        }
        return this;
    };

    self.or = function(values) {
        if (Array.isArray(values)) {
            this.q.conditions['or'] = values;
        }
        return this;
    };

    self.range = function(key, from, to) {
        if (typeof to === 'undefined') {
            if (this.q.pkey) {
                to = from;
                from = key;
                if (typeof this.q.conditions[this.q.pkey] === 'undefined') {
                    this.q.conditions[this.q.pkey] = {};
                }
                this.q.conditions[this.q.pkey].gt = from;
                this.q.conditions[this.q.pkey].lt = to;
            }
        } else {
            this.q.pkey = false;
            if (typeof this.q.conditions[key] === 'undefined') {
                this.q.conditions[key] = {};
            }
            this.q.conditions[key].gt = from;
            this.q.conditions[key].lt = to;
        }
        return this;
    };

    ['gt', 'gte', 'lt', 'lte', 'in', 'inq', 'ne', 'neq', 'nin', 'regex', 'like', 'nlike', 'between'].forEach(function(method) {
        self[method] = function(key, value) {
            if (typeof value === 'undefined') {
                if (this.q.pkey) {
                    if (typeof this.q.conditions[this.q.pkey] === 'undefined') {
                        this.q.conditions[this.q.pkey] = {};
                    }
                    this.q.conditions[this.q.pkey][method] = key;
                }
            } else {
                this.q.pkey = false;
                if (typeof this.q.conditions[key] === 'undefined') {
                    this.q.conditions[key] = {};
                }
                this.q.conditions[key][method] = value;
            }
            return this;
        };
    });

    self.slice = function(values) {
        if (Array.isArray(values)) {
            if (typeof values[1] === 'undefined') {
                this.q.params['limit'] = values[0];
            } else {
                this.q.params['skip'] = values[0];
                this.q.params['limit'] = values[1];
            }
        }
        return this;
    };

    /**
     * Destroy records
     * @param {Object} params
     * @param {Function} callback
     */
    self.remove = function(params, callback) {
        if (arguments.length === 1) {
            callback = params;
            params = {};
        }
        params = buildQuery(params, this);
        self.model.remove(params, callback);
    };

    function buildQuery(opts, query) {
        if (typeof opts.where === 'undefined') {
            opts.where = {};
        }
        opts.where = helpers.merge(opts.where, query.q.conditions);
        query.q.conditions = {};

        for (var pkey in query.q.params) {
            if (typeof opts[pkey] === 'undefined') {
                opts[pkey] = {};
            }
            opts[pkey] = query.q.params[pkey];
        }

        query.q.params = {};
        query.q.pkey = false;
        return opts;
    }
}
969120
public function beforeLoad($m, $q = null)
    {
        if (is_null($q)) {
            return;
        }  // manual load

        if ($this->m2 && $this->m2 != $this->owner->id_field) {
            $q->field($this->m2, $this->m1, $this->short_name);
        } elseif ($this->m2) {
            $q->field($this->f2, $this->fa ?: $this->f1, $this->short_name);
        }
    }
842502
protected function setLimitOrder($m, $q)
    {
        if ($m->limit && ($m->limit[0] || $m->limit[1])) {
            if ($m->limit[0] === null) {
                // This is max number which is allowed in MySQL server.
                // But be aware, that PDO will downgrade this number even lower probably because
                // in LIMIT it expects numeric value and converts string (we set float values as PDO_PARAM_STR)
                // back to PDO_PARAM_INT which is goes back to max int value specific server can have.
                // On my Win10,64-bit it is 2147483647, on Travis server 9223372036854775807 etc.
                $m->limit[0] = '18446744073709551615';
            }
            $q->limit($m->limit[0], $m->limit[1]);
        }

        if ($m->order) {
            foreach ($m->order as $o) {
                $q->order($m->getField($o[0]), $o[1]);
            }
        }
    }
421389
public function search($q)
    {
        /* @var \Doctrine\ODM\MongoDB\Query\Builder $qb */
        $qb = $this->repository->createQueryBuilder();
        $qb->field('title')->equals(new \MongoRegex('/' . addslashes($q) . '/i'));
        $cursor = $qb->getQuery()->execute();

        $adapter = new DoctrineMongoCursor($cursor);
        parent::__construct($adapter);

        return $this;
    }
991456
public function prepareIterator(Model $m)
    {
        try {
            $export = $m->action('select');

            return $export->execute();
        } catch (\PDOException $e) {
            throw new Exception([
                'Unable to execute iteration query',
                'query'      => $export->getDebugQuery(false),
                'model'      => $m,
                'conditions' => $m->conditions,
            ], null, $e);
        }
    }
962021
public function query(string $q): \PDOStatement
    {
        try {
            $_SESSION['___QUERY_DEBUG___'][] = (string) $q;

            return parent::query($q);
        } catch (\Exception $e) {
            $message = 'Error in query: <b>' . $q . '<b/><br /><br />' . $e->getMessage();
        }
    }
910905
public static function make($query, Model $model = null)
    {
        if ($query instanceof EloquentBuilder) {
            $model = $query->getModel();
            $query = $query->getQuery();
        }

        return new Joiner($query, $model);
    }
571776
public function joinFrom($model, $thisKeyCol, $thatKeyCol=null, $conditions='')
	{
		if( $thatKeyCol===null )
		{
			debug_assert( $thisKeyCol!==null );
			$thatKeyCol = $model->getPrimaryKey();
		}
		elseif( $thisKeyCol===null )
		{
			debug_assert( $thatKeyCol!==null );
			$thisKeyCol = $this->getPrimaryKey();
		}

		$this->prefixColumn($model, $thatKeyCol);
		$this->prefixColumn($this, $thisKeyCol);

		$conditions = str_replace('{that}', $model->getAlias(), $conditions);
		$conditions = str_replace('{this}', $this->getAlias(), $conditions);

		$this->mapPartWhere( $this->addAliasToConditionDg() );
		$model->mapPartWhere( $model->addAliasToConditionDg() );

		$thisFrom = $this->_select->getPart(Zend_Db_Select::FROM);
		$modelColumns = array_chain(
			$model->_select->getPart(Zend_Db_Select::COLUMNS),
			array_group_dg( array_get_dg(return_dg(0)) ),
			array_map_val_dg(
				array_chain_dg(
					array_map_val_dg(
						function($descriptor)
						{
							return null===$descriptor[2]
								? $descriptor[1]
								: [ $descriptor[2] => $descriptor[1] ]
							;
						}
					),
					function($columns){
						$outArray = [];
						array_map_val($columns, function($column)use(&$outArray){
							if(is_array($column))
							{
								array_map_val($column, function($column, $alias)use(&$outArray){
									$outArray[$alias] = $column;
								});
							}
							else
							{
								$outArray[] = $column;
							}
						});
						
						return $outArray;
					}
				)
			)
		);

		array_each(
			$model->_select->getPart(Zend_Db_Select::FROM),
			function( $descriptor, $alias )use($modelColumns,$thisFrom,$model,$thisKeyCol,$thatKeyCol,$conditions)
			{
				debug_enforce(
					!array_key_exists( $alias, $thisFrom ),
					"Alias `{$alias}` already used for table `{$descriptor['tableName']}`"
				);

				switch( $descriptor['joinType'] )
				{
					case Zend_Db_Select::FROM:
						$this->_select->joinLeft(
							[$model->getAlias()=>$model->getTable()],
							"{$thisKeyCol}={$thatKeyCol} ".$conditions,
							array_key_exists( $alias, $modelColumns ) ? $modelColumns[ $alias ] : [],
							$descriptor[ 'schema' ]
						);
					break;
					case Zend_Db_Select::INNER_JOIN:
						$this->_select->joinInner(
							[$alias=>$descriptor['tableName']],
							$descriptor['joinCondition'],
							array_key_exists( $alias, $modelColumns ) ? $modelColumns[ $alias ] : [],
							$descriptor['schema']
						);
					break;
					case Zend_Db_Select::LEFT_JOIN:
						$this->_select->joinLeft(
							[$alias=>$descriptor['tableName']],
							$descriptor['joinCondition'],
							array_key_exists( $alias, $modelColumns ) ? $modelColumns[ $alias ] : [],
							$descriptor['schema']
						);
					break;
					case Zend_Db_Select::RIGHT_JOIN:
						$this->_select->joinRight(
							[$alias=>$descriptor['tableName']],
							$descriptor['joinCondition'],
							array_key_exists( $alias, $modelColumns ) ? $modelColumns[ $alias ] : [],
							$descriptor['schema']
						);
					break;
					case Zend_Db_Select::FULL_JOIN:
						$this->_select->joinFull(
							[$alias=>$descriptor['tableName']],
							$descriptor['joinCondition'],
							array_key_exists( $alias, $modelColumns ) ? $modelColumns[ $alias ] : [],
							$descriptor['schema']
						);
					break;
					case Zend_Db_Select::CROSS_JOIN:
						$this->_select->joinCross(
							[$alias=>$descriptor['tableName']],
							$descriptor['joinCondition'],
							array_key_exists( $alias, $modelColumns ) ? $modelColumns[ $alias ] : [],
							$descriptor['schema']
						);
					break;
					case Zend_Db_Select::NATURAL_JOIN:
						$this->_select->joinNatural(
							[$alias=>$descriptor['tableName']],
							$descriptor['joinCondition'],
							array_key_exists( $alias, $modelColumns ) ? $modelColumns[ $alias ] : [],
							$descriptor['schema']
						);
					break;
					default:
						debug_assert( false, "Unknown join type ".var_dump_human_compact($descriptor['joinType']));
					break;
				}
			}
		);

		$this->settingsJoin($model);

		return $this;
	}
378485
public function loadAny(Model $m)
    {
        $data = $this->tryLoadAny($m);

        if (!$data) {
            throw new Exception([
                'No matching records were found',
                'model'      => $m,
                'conditions' => $m->conditions,
            ], 404);
        }

        return $data;
    }
823454
public static function query($alias = null, $model = null)
    {
        if (!$model) {
            $model = Di::getDefault()->getShared(static::class);
        }

        return $model->_di->get('ManaPHP\Mongodb\Query')->setModel($model)->setTypes($model->getFieldTypes());
    }