/
v.bolshakov
/
AIEcosystem-Testing
Обзор
Документация
Войти
/
v.bolshakov
/
AIEcosystem-Testing
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
dev
common/models/base/BaseQuery.php
300 строк
9 KB
Developer
Initial commit
03 авг 2026, 17:43
03 авг 2026, 17:43
7433917
Код
Авторство
О чём код?
<?php namespace common\models\base; use common\kdf\KModelStatus; use Yii; use yii\db\ActiveQuery; use yii\db\ActiveRecord; use yii\helpers\ArrayHelper; use yii\web\BadRequestHttpException; /** * Базовый класс BaseQuery * * @author Dmitry E. Semenov <sde.tomsk@gmail.com> * @copyright Self (c) 2019 */ class BaseQuery extends ActiveQuery { /** * Получить алиас для построения запроса * @return string */ public function getAlias() { /** @var ActiveRecord $class */ $class = $this->modelClass; return $class::getAlias(); } /** * Выбрать не удалённые записи * @return mixed */ public function notDeleted() { $object = new $this->modelClass; if ($object->hasAttribute('rec_status')) { // проверяем на статус записи $this ->alias($this->alias) ->andWhere(['!=', $this->alias . '.rec_status', KModelStatus::DELETED]); } return $this; } /** * Выбрать только активные записи * @return mixed */ public function published($model_status = KModelStatus::PUBLISHED) { $object = new $this->modelClass; if ($object->hasAttribute('rec_status')) { return $this ->alias($this->alias) ->andWhere([$this->alias . '.rec_status' => $model_status]); } else { return $this; } } /** * Фильтрация данных * * @param array $fields - список полей по которым ищем * @param string $value - фильтрующее значение * @param array $options - параметры фильтрации * $from_begin - искать с начала текста или любое вхождение * $with_alias - подставлять алиасы таблиц * $split_search - разбивать поиск по словам и столбцам или нет * $strong_filter - искать каждое поле в своём столбце или все поля во всех стоблца * * @return $this */ public function filterData( $fields, $value, $options = [] ) { $value = mb_strtolower(trim($value)); $from_begin = ArrayHelper::getValue($options, 'from_begin', false); $with_alias = ArrayHelper::getValue($options, 'with_alias', true); $split_search = ArrayHelper::getValue($options, 'split_search', true); $strong_filter = ArrayHelper::getValue($options, 'strong_filter', false); $operation = ArrayHelper::getValue($options, 'operation', 'and'); $search = []; $fields_count = count($fields); if ($split_search) { $values = explode(' ', $value); } else { $values = [$value]; } foreach ($values as $value) { if ($value) { if ($from_begin) { $search[] = $value . '%'; } else { $search[] = $value; } } } $cnt = count($search); if ($cnt > 0) { $a = $with_alias ? $this->alias . '.' : ''; $contition = []; if ($cnt == 1) { $contition[] = 'or'; foreach ($fields as $field => $field_alias) { if (is_int($field)) { $the_field = $field_alias; } else { $the_field = $field; $a = $field_alias . '.'; } $contition[] = [ 'or like', 'lower(' . $a . $the_field . ')', $search[0], $from_begin ? false : null ]; } } else { $index = 0; $contition[] = $operation; if ($fields_count == 1) { $field_alias = array_keys($fields); if (!is_int($field_alias) and !is_array($field_alias)) { $a = $field_alias . '.'; } $the_field = array_shift($fields); foreach ($search as $search_part) { $contition[] = [ 'or like', 'lower(' . $a . $the_field . ')', $search_part, ($from_begin and $index == 0) ? false : null ]; $index++; } } else { foreach ($fields as $field => $field_alias) { if (is_int($field)) { $the_field = $field_alias; } else { $the_field = $field; $a = $field_alias . '.'; } if ($strong_filter) { // поиск все слова во всех столбцах $sub = []; $sub[] = 'or'; foreach ($search as $search_part) { $sub[] = [ 'or like', 'lower(' . $a . $the_field . ')', $search_part, $from_begin ? false : null ]; } $contition[] = $sub; } else { // поиск каждого слова по своему столбцу $contition[] = [ 'or like', 'lower(' . $a . $the_field . ')', $search[$index], $from_begin ? false : null ]; } $index++; if ($index >= $cnt) { break; } } } } $this ->alias($this->alias) ->andWhere($contition); } return $this; } /** * Поиск по параметрам gtp_id или erp_id * * @param array $data * @return BaseQuery * @throws BadRequestHttpException */ public function prepareById($data = []) { $a = $this->alias; if ($gtp_id = ArrayHelper::getValue($data, 'gtp_id')) { $this->andWhere([ $a . '.id' => $gtp_id ]); } elseif ($erp_id = ArrayHelper::getValue($data, 'erp_id')) { $this->andWhere([ $a . '.erp_id' => $erp_id ]); } else { $class = $this->modelClass; throw new BadRequestHttpException(Yii::t('app', 'One of param «gtp_id» or «erp_id» in class «{0}» must be set', [ basename($class) ])); } return $this->alias($a); } /** * Получить имя поля вместе с алиасом * * @param $field * * @return string */ public function getFieldWithAlias($field) { return $this->getAlias() . '.' . $field; } /** * Сортировать - сперва новые значения * @return $this */ public function last() { $modelClass = $this->modelClass; $order = []; foreach ($modelClass::primaryKey() as $primaryKey) { $order[$this->alias . '.' . $primaryKey] = SORT_DESC; } return $this ->alias($this->alias) ->orderBy($order); } /** * Сортировать - сперва старые значения * @return $this */ public function first() { $modelClass = $this->modelClass; $order = []; foreach ($modelClass::primaryKey() as $primaryKey) { $order[$this->alias . '.' . $primaryKey] = SORT_ASC; } return $this ->alias($this->alias) ->orderBy($order); } /** * Сортировка по номерам в модели * * @param string $column * @return $this */ public function orderByNumber($column = 'order_number') { $a = $this->alias; return $this ->alias($a) ->orderBy([$a . '.' . $column => SORT_ASC]); } public function prepareParentModel($field_name, $parent_id, $model) { return $this ->andWhere([$field_name => $parent_id]); } }