/** * @param ActiveQuery $query * @param string $attribute * @param bool $partialMath */ private function addCondition($query, $attribute, $partialMath = false) { if (isset($this->relationAttributes[$attribute])) { $attributeName = $this->relationAttributes[$attribute]; } else { $attributeName = call_user_func([$this->modelClassName, 'tableName']) . '.' . $attribute; } $value = $this->{$attribute}; if ($value === '') { return; } if ($partialMath) { $query->andWhere(['like', $attributeName, $value]); } else { $query->andWhere([$attributeName => $value]); } }
/** * Configures the query as such, that you can filter by a model, its id or an array of both. It is also * possible to invert the query. This means all but the one(s) provided. * * @param \yii\db\ActiveQuery $query the query to modify * @param integer|integer[]|\yii\db\ActiveRecord|\yii\db\ActiveRecord[] $param the id(s) or the model(s). If * an array is provided, it can be a mix of both * @param string $attribute the attribute name to compare (defaults to `id`) * @param bool $invert if true t, the query will be inverted (NOT LIKE, NOT, ...) */ public function oneOrManyModelComparison(&$query, $param, $attribute = 'id', $invert = false) { //get data from array if (is_array($param)) { $data = []; foreach ($param as $p) { if ($p instanceof \yii\db\ActiveRecord) { $data[] = $p->{$attribute}; } else { $data[] = $p; } } $param = $data; } else { if ($param instanceof \yii\db\ActiveRecord) { $param = $param->{$attribute}; } } //modify query if (!$invert) { $query->andWhere([$attribute => $param]); } else { $query->andWhere(['not', [$attribute => $param]]); } }
/** * @param array $params */ public function setParams($params = []) { foreach ($params as $col => $value) { $this->query->andWhere(['like', $col, [$value]]); $this->countQuery->orWhere([$col => $value]); } }
public function getDataprovider() { $query = new ActiveQuery($this::className()); if ($this->airport_id) { $query->andWhere(['airport_id' => $this->airport_id]); } $query->andWhere(['isarrival' => $this->isarrival]); $query->orderBy($this->isarrival == 1 ? "timeto" : "timefrom"); return new ActiveDataProvider(['query' => $query]); }
/** * Use a distinct compare value for each column. Primary and foreign keys support multiple values. * @param \yii\db\ActiveQuery $query * @return \yii\db\ActiveQuery */ protected function addAttributesSearchConditions(\yii\db\ActiveQuery $query) { $tablePrefix = $this->getDb()->getSchema()->quoteSimpleTableName('t'); $conditions = ['and']; $formats = $this->attributeFormats(); $attributes = $this->attributes(); $relations = $this->relations(); $validAttributes = array_diff($attributes, array_keys($this->getErrors())); $attributeValues = $this->getAttributes($validAttributes); $formatter = Yii::$app->formatter; /** @var EnumCollection $enums */ $enums = $formatter instanceof Formatter ? $formatter->getEnums() : null; foreach ($validAttributes as $attribute) { $value = $attributeValues[$attribute]; if ($value === null || !isset($formats[$attribute]) || $enums !== null && !is_array($formats[$attribute]) && $enums->has($formats[$attribute])) { continue; } if (in_array($attribute, $relations)) { // only hasMany relations should be ever marked as valid attributes $conditions[] = $this->getRelationCondition($this->getRelation($attribute), $value); } else { $conditions[] = $this->getAttributeCondition($attribute, $value, $formats, $tablePrefix, $this->getDb()); } } // don't clear attributes to allow rendering filled search form //$this->setAttributes(array_fill_keys($attributes, null)); if ($conditions !== ['and']) { $query->andWhere($conditions); } return $query; }
public static function getActiveToken($token) { $activeQuery = new ActiveQuery(self::className()); $activeQuery->where('access_token = :token', [':token' => $token]); $activeQuery->andWhere('expires > now()'); $token = $activeQuery->one(); return $token; }
public function filterQuery(ActiveQuery $query) { if ($this->type) { $query->innerJoinWith('type'); $query->andWhere(['{{death_reason_type}}.[[key]]' => $this->type]); } return $query; }
/** * @param ActiveQuery $query * @param $attribute * @param bool|false $partialMatch */ protected function addCondition(ActiveQuery $query, $attribute, $partialMatch = false) { if (($pos = strrpos($attribute, '.')) !== false) { $modelAttribute = substr($attribute, $pos + 1); } else { $modelAttribute = $attribute; } $value = $this->{$modelAttribute}; if (trim($value) === '') { return; } $attribute = "books.{$attribute}"; if ($partialMatch) { $query->andWhere(['like', $attribute, $value]); } else { $query->andWhere([$attribute => $value]); } }
public function filterQuery(ActiveQuery $query) { if ($this->weapon) { $query->andWhere(['{{weapon}}.[[key]]' => $this->weapon]); } if ($this->type) { $query->innerJoinWith('type'); $query->andWhere(['{{weapon_type}}.[[key]]' => $this->type]); } if ($this->sub) { $query->innerJoinWith('subweapon'); $query->andWhere(['{{subweapon}}.[[key]]' => $this->sub]); } if ($this->special) { $query->innerJoinWith('special'); $query->andWhere(['{{special}}.[[key]]' => $this->special]); } return $query; }
public function filter(ActiveQuery $query, &$cacheKeyAppend) { $get = Yii::$app->request->post(); if (isset($get['changeValue']) && is_array($get['changeValue'])) { foreach ($get['changeValue'] as $propertyId => $isActive) { if ($isActive && isset($get[$this->minValueAttribute][$propertyId]) && isset($get[$this->maxValueAttribute][$propertyId]) && is_numeric($get[$this->minValueAttribute][$propertyId]) && is_numeric($get[$this->maxValueAttribute][$propertyId])) { $property = Property::findById($propertyId); if ($property->has_static_values) { $query->innerJoin('{{%object_static_values}} as osvf' . $propertyId, '{{%product}}.id=osvf' . $propertyId . '.object_model_id'); $query->innerJoin('{{%property_static_values}} as psvf' . $propertyId, 'psvf' . $propertyId . '.id=osvf' . $propertyId . '.property_static_value_id'); $query->andWhere('psvf' . $propertyId . '.value >= :minData ')->andWhere('psvf' . $propertyId . '.value <= :maxData ')->andWhere(['psvf' . $propertyId . '.property_id' => $propertyId])->addParams([':minData' => (int) $get[$this->minValueAttribute][$propertyId], ':maxData' => (int) $get[$this->maxValueAttribute][$propertyId]]); } elseif ($property->is_eav) { $query->innerJoin('{{%product_eav}} as peav' . $propertyId, '{{%product}}.id=peav' . $propertyId . '.object_model_id'); $query->andWhere(['peav' . $propertyId . '.property_group_id' => $property->property_group_id, 'peav' . $propertyId . '.key' => $property->key]); $query->andWhere(['>=', 'peav' . $propertyId . '.value', (int) $get[$this->minValueAttribute][$propertyId]]); $query->andWhere(['<=', 'peav' . $propertyId . '.value', (int) $get[$this->maxValueAttribute][$propertyId]]); } $cacheKeyAppend .= 'FilterRangeProperty:propertyId' . $propertyId . ':[min:' . (int) $get[$this->minValueAttribute][$propertyId] . ':max' . (int) $get[$this->maxValueAttribute][$propertyId] . ']'; } } } return $query; }
public function filter(ActiveQuery $query, &$cacheKeyAppend) { $get = Yii::$app->request->post(); if (isset($get['changeValue']) && is_array($get['changeValue'])) { foreach ($get['changeValue'] as $propertyId => $isActive) { if ($isActive && isset($get[$this->minValueAttribute][$propertyId]) && isset($get[$this->maxValueAttribute][$propertyId]) && is_numeric($get[$this->minValueAttribute][$propertyId]) && is_numeric($get[$this->maxValueAttribute][$propertyId])) { $query->innerJoin('object_static_values as osvf' . $propertyId, 'product.id=osvf' . $propertyId . '.object_model_id'); $query->innerJoin('property_static_values as psvf' . $propertyId, 'psvf' . $propertyId . '.id=osvf' . $propertyId . '.property_static_value_id'); $query->andWhere('psvf' . $propertyId . '.value >= :minData ')->andWhere('psvf' . $propertyId . '.value <= :maxData ')->andWhere(['psvf' . $propertyId . '.property_id' => $propertyId])->addParams([':minData' => (int) $get[$this->minValueAttribute][$propertyId], ':maxData' => (int) $get[$this->maxValueAttribute][$propertyId]]); $cacheKeyAppend .= 'FilterRangeProperty[min:' . (int) $get[$this->minValueAttribute][$propertyId] . ':max' . (int) $get[$this->maxValueAttribute][$propertyId] . ']'; } } } return $query; }
/** * Setup additional filters */ public function setupFilters() { if (in_array('entry_files', $this->filters)) { $fileSelector = (new \yii\db\Query())->select(["id"])->from('file')->where('file.object_model=content.object_model AND file.object_id=content.object_id')->limit(1); $fileSelectorSql = Yii::$app->db->getQueryBuilder()->build($fileSelector)[0]; $this->activeQuery->andWhere('(' . $fileSelectorSql . ') IS NOT NULL'); } // Setup Post specific filters if (in_array('posts_links', $this->filters)) { $this->activeQuery->leftJoin('post', 'content.object_id=post.id AND content.object_model=:postModel', ['postModel' => \humhub\modules\post\models\Post::className()]); $this->activeQuery->andWhere("post.url is not null"); } // Only apply archived filter when we should load more than one entry if ($this->limit != 1) { if (!in_array('entry_archived', $this->filters)) { $this->activeQuery->andWhere("(content.archived != 1 OR content.archived IS NULL)"); } } // Show only mine items if (in_array('entry_mine', $this->filters) && $this->user !== null) { $this->activeQuery->andWhere(['content.created_by' => $this->user->id]); } // Show only items where the current user is involed if (in_array('entry_userinvoled', $this->filters) && $this->user !== null) { $this->activeQuery->leftJoin('user_follow', 'content.object_model=user_follow.object_model AND content.object_id=user_follow.object_id AND user_follow.user_id = :userId', ['userId' => $this->user->id]); $this->activeQuery->andWhere("user_follow.id IS NOT NULL"); } if (in_array('model_posts', $this->filters)) { $this->activeQuery->andWhere(["content.object_model" => \humhub\modules\post\models\Post::className()]); } // Visibility filters if (in_array('visibility_private', $this->filters)) { $this->activeQuery->andWhere(['content.visibility' => Content::VISIBILITY_PRIVATE]); } if (in_array('visibility_public', $this->filters)) { $this->activeQuery->andWhere(['content.visibility' => Content::VISIBILITY_PUBLIC]); } }
protected function _run() { $key = $this->getCacheKey() . 'run'; $dependency = new TagDependency(['tags' => [$this->className() . (string) $this->namespace, (new Tree())->getTableCacheTag()]]); $result = \Yii::$app->cache->get($key); if ($result === false || $this->enabledRunCache == Cms::BOOL_N) { $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) { $this->activeQuery->andWhere(['site_code' => $this->site_codes]); } if ($this->enabledCurrentSite == Cms::BOOL_Y && ($currentSite = \Yii::$app->cms->site)) { $this->activeQuery->andWhere(['site_code' => $currentSite->code]); } 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); } $result = parent::_run(); \Yii::$app->cache->set($key, $result, (int) $this->runCacheDuration, $dependency); } return $result; }
/** * Конфигурирование объекта запроса поиска по элементам. * * @param \yii\db\ActiveQuery $activeQuery * @param null $modelClassName * @return $this */ public function buildElementsQuery(\yii\db\ActiveQuery $activeQuery) { $where = []; //Нужно учитывать связанные дополнительные данные if ($this->enabledElementProperties == Cms::BOOL_Y) { $activeQuery->joinWith('cmsContentElementProperties'); //Нужно учитывать настройки связанные дополнительные данных if ($this->enabledElementPropertiesSearchable == Cms::BOOL_Y) { $activeQuery->joinWith('cmsContentElementProperties.property'); $where[] = ['and', ['like', CmsContentElementProperty::tableName() . ".value", '%' . $this->searchQuery . '%', false], [CmsContentProperty::tableName() . ".searchable" => Cms::BOOL_Y]]; } else { $where[] = ['like', CmsContentElementProperty::tableName() . ".value", '%' . $this->searchQuery . '%', false]; } } //Поиск по основному набору полей if ($this->searchElementFields) { foreach ($this->searchElementFields as $fieldName) { $where[] = ['like', CmsContentElement::tableName() . "." . $fieldName, '%' . $this->searchQuery . '%', false]; } } if ($where) { $where = array_merge(['or'], $where); $activeQuery->andWhere($where); } //Отфильтровать только конкретный тип if ($this->searchElementContentIds) { $activeQuery->andWhere([CmsContentElement::tableName() . ".content_id" => (array) $this->searchElementContentIds]); } return $this; }
/** * Adds an additional WHERE condition to the existing one. * * @inheritdoc * * @param type $condition * @param type $params * @return type */ public function where($condition, $params = array()) { return parent::andWhere($condition, $params); }
/** * * Apply current condition will be applied to a query using this function. * * @param \yii\db\ActiveQuery $query The query object which current condition must be applied to */ public function prepareQuery($query) { $field = $this->functionObj->prepareSql(); if (!$field) { return NULL; } switch ($this->operation) { case 'select': // Here I need to add property to the target class accroding to alias $query->addSelect([$this->alias => $field]); break; case 'where': $query->andWhere($field); break; case 'group': $query->addGroupBy($field); break; case 'order': $query->addOrderBy($field); break; case 'order_inv': $query->addOrderBy([$field => SORT_DESC]); break; } }
public static function whereFromTo(ActiveQuery $query, $fromTime, $toTime = null, $column = '{{record}}.start') { $timezone = new \DateTimeZone(\Yii::$app->timeZone); if ($fromTime) { $from = (new \DateTime('@' . $fromTime))->setTimezone($timezone); $query->andWhere($column . ' >= :today', [':today' => $from->format('c')]); } if ($toTime) { $to = (new \DateTime('@' . $toTime))->setTimezone($timezone); $query->andWhere($column . ' < :todayNight', [':todayNight' => $to->format('c')]); } return $query; }
public function byHour() { return parent::andWhere('timestamp>:time', [':time' => time() - 3600]); }
public static function find() { $query = new ActiveQuery(get_called_class()); $query->andWhere('isActive = 1'); return $query; }
/** * @param ActiveQuery $query */ public function decorateQuery($query) { if ($this->typification) { $query->andWhere([$this->tableName() . '.' . $this->typeField => $this->type]); } if ($this->softDelete) { $query->andWhere([$this->tableName() . '.' . $this->deleteField => null]); } }
/** * @param ActiveQuery $queryBuilder * @param Parameter $parameter */ protected function attachParameterToQueryBuilder(&$queryBuilder, $parameter) { switch ($parameter->getComparison()) { case Comparison::AFTER: case Comparison::GREATER_THAN: $queryBuilder->andWhere(['>', $parameter->getDatabaseFilterField(), $parameter->getDatabaseFilterValue()[0]]); break; case Comparison::BEFORE: case Comparison::LESS_THAN: $queryBuilder->andWhere(['<', $parameter->getDatabaseFilterField(), $parameter->getDatabaseFilterValue()[0]]); break; case Comparison::BETWEEN: $queryBuilder->andWhere(['between', $parameter->getDatabaseFilterField(), $parameter->getDatabaseFilterValue()[0], $parameter->getDatabaseFilterValue()[1]]); break; case Comparison::CONTAINS: $queryBuilder->andWhere(['like', $parameter->getDatabaseFilterField(), $parameter->getDatabaseFilterValue()[0]]); break; case Comparison::STARTS_WITH: $queryBuilder->andWhere(['like', $parameter->getDatabaseFilterField(), $parameter->getDatabaseFilterValue()[0] . '%', false]); break; case Comparison::ENDS_WITH: $queryBuilder->andWhere(['like', $parameter->getDatabaseFilterField(), '%' . $parameter->getDatabaseFilterValue()[0], false]); break; case Comparison::NULL: $queryBuilder->andWhere([$parameter->getDatabaseFilterField() => null]); break; case Comparison::NOT_NULL: $queryBuilder->andWhere(['not', [$parameter->getDatabaseFilterField() => null]]); break; case Comparison::EQUALS: $queryBuilder->andWhere([$parameter->getDatabaseFilterField() => $parameter->getDatabaseFilterValue()[0]]); break; case Comparison::NOT_EQUALS: $queryBuilder->andWhere(['not', [$parameter->getDatabaseFilterField() => $parameter->getDatabaseFilterValue()[0]]]); break; case Comparison::ONE_OF: $queryBuilder->andWhere(['in', $parameter->getDatabaseFilterField(), $parameter->getDatabaseFilterValue()]); break; } $additionalFilter = $parameter->getAdditionalDatabaseFilter(); if ($additionalFilter instanceof \Closure) { $additionalFilter($queryBuilder); } }