本文整理汇总了PHP中yii\db\ActiveQuery类的典型用法代码示例。如果您正苦于以下问题:PHP ActiveQuery类的具体用法?PHP ActiveQuery怎么用?PHP ActiveQuery使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了ActiveQuery类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: oneOrManyModelComparison
/**
* 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]]);
}
}
示例2: addAttributesSearchConditions
/**
* 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;
}
示例3: getActiveToken
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;
}
示例4: filterQuery
public function filterQuery(ActiveQuery $query)
{
if ($this->type) {
$query->innerJoinWith('type');
$query->andWhere(['{{death_reason_type}}.[[key]]' => $this->type]);
}
return $query;
}
示例5: getDataprovider
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]);
}
示例6: getSortConfig
/**
* Creates a Sort object configuration using query default order.
* @param \yii\db\ActiveQuery $query
* @param array $attributes
* @return array
*/
public function getSortConfig(\yii\db\ActiveQuery $query, array $attributes)
{
$defaults = $query instanceof ActiveQuery ? $query->getDefaultOrderColumns() : [];
$sort = ['enableMultiSort' => true, 'attributes' => [], 'defaultOrder' => $defaults];
/** @var TableSchema $tableSchema */
$tableSchema = $this->getTableSchema();
foreach ($attributes as $attribute) {
if ($tableSchema->getColumn($attribute) === null) {
continue;
}
$sort['attributes'][$attribute] = ['asc' => array_merge([$attribute => SORT_ASC], $defaults), 'desc' => array_merge([$attribute => SORT_DESC], $defaults)];
}
return $sort;
}
示例7: filter
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;
}
示例8: buildElementsQuery
/**
* Конфигурирование объекта запроса поиска по элементам.
*
* @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;
}
示例9: findx
/**
* @param $table
* @return object
* @throws InvalidConfigException
*/
public static function findx($table)
{
if (self::$table != $table) {
self::$table = $table;
}
return Yii::createObject(ActiveQuery::className(), [get_called_class(), ['from' => [static::tableName()]]]);
}
示例10: processSearchRelated
/**
* Adds a condition to search in relations using subquery.
* @todo this should be called for each token, to group their conditions with OR and group token groups with AND
*
* @param \yii\db\ActiveQuery $query
* @param array $tokens all search tokens extracted from term
* @param array $relationAttributes array of string(relation name) => array(
* 'model' => netis\crud\db\ActiveRecord,
* 'searchModel' => netis\crud\db\ActiveSearchTrait,
* 'attributes' => array
* )
* @return array conditions to add to $query
*/
protected function processSearchRelated(\yii\db\ActiveQuery $query, array $tokens, array $relationAttributes)
{
$allConditions = ['or'];
foreach ($relationAttributes as $relationName => $relation) {
/**
* @todo optimize this (check first, don't want to loose another battle with PostgreSQL query planner):
* - for BELONGS_TO check fk against subquery
* - for HAS_MANY and HAS_ONE check pk against subquery
* - for MANY_MANY join only to pivot table and check its fk agains subquery
*/
$query->joinWith([$relationName => function ($query) use($relationName) {
/** @var \yii\db\ActiveQuery $query */
/** @var \yii\db\ActiveRecord $class */
$class = $query->modelClass;
return $query->select(false)->from([$relationName => $class::tableName()]);
}]);
$conditions = ['and'];
/** @var ActiveSearchInterface $searchModel */
$searchModel = $relation['searchModel'];
if (!$searchModel instanceof ActiveSearchInterface) {
continue;
}
foreach ($tokens as $token) {
$condition = $searchModel->processSearchToken($token, $relation['attributes'], $relationName);
if ($condition !== null) {
$conditions[] = $condition;
}
}
if ($conditions !== ['and']) {
$allConditions[] = $conditions;
}
}
return $allConditions !== ['or'] ? $allConditions : null;
}
示例11: applyOrder
/**
* Apply possible answers order to query
* @param ActiveQuery $query
* @param $order
* @return string
*/
public static function applyOrder(ActiveQuery $query, $order)
{
switch ($order) {
case 'oldest':
$query->orderBy('created_at DESC');
break;
case 'active':
$query->orderBy('created_at ASC');
break;
case 'votes':
default:
$query->orderBy('votes DESC');
break;
}
return $order;
}
示例12: run
/**
* @inheritdoc
*/
public function run()
{
$countQuery = clone $this->query;
$pagination = new \yii\data\Pagination(['totalCount' => $countQuery->count(), 'pageSize' => $this->pageSize]);
$this->query->offset($pagination->offset)->limit($pagination->limit);
return $this->render("userListBox", ['title' => $this->title, 'users' => $this->query->all(), 'pagination' => $pagination]);
}
示例13: _run
protected function _run()
{
$key = $this->getCacheKey() . 'run';
$dependency = new TagDependency(['tags' => [$this->className() . (string) $this->namespace, (new CmsSite())->getTableCacheTag()]]);
$result = \Yii::$app->cache->get($key);
if ($result === false || $this->enabledRunCache == Cms::BOOL_N) {
$this->activeQuery = CmsSite::find();
if ($this->active == Cms::BOOL_Y) {
$this->activeQuery->active();
} else {
if ($this->active == Cms::BOOL_N) {
$this->activeQuery->active(false);
}
}
if ($this->limit) {
$this->activeQuery->limit($limit);
}
if ($this->orderBy) {
$this->activeQuery->orderBy([$this->orderBy => (int) $this->order]);
}
$result = parent::_run();
\Yii::$app->cache->set($key, $result, (int) $this->runCacheDuration, $dependency);
}
return $result;
}
示例14: sort
/**
* @param int $sort
* @return $this
*/
public function sort($sort = SORT_DESC)
{
/** @var ISortableActiveRecord $model */
$model = new $this->owner->modelClass();
$behavior = $model->getSortBehavior();
$this->owner->orderBy([$behavior->attributeName => $sort]);
return $this;
}
示例15: getPaginator
/**
* @return Pagination
*/
public function getPaginator()
{
$paginator = new Pagination(['totalCount' => $this->countQuery->count()]);
$paginator->pageParam = 'page';
$paginator->pageSizeParam = false;
$paginator->setPageSize($this->limit);
return $paginator;
}