ar-search

Provides unified search model for Yii ActiveRecord

Github星跟踪图

This extension provides unified search model for Yii ActiveRecord.

For license information check the LICENSE-file.

Latest Stable Version
Total Downloads
Build Status

Installation

The preferred way to install this extension is through composer.

Either run

php composer.phar require --prefer-dist yii2tech/ar-search

or add

"yii2tech/ar-search": "*"

to the require section of your composer.json.

Usage

This extension provides unified search model for Yii ActiveRecord via special model class -
.

This model is able to fetch its attributes, validation rules and filtering logic from the 'slave'
source ActiveRecord model specified via .
Thus you do not need to declare a separated model class for searching and define a filter logic.
For example:

use yii2tech\ar\search\ActiveSearchModel;

$searchModel = new ActiveSearchModel([
    'model' => 'app\models\Item'
]);
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);

ActiveSearchModel picks all 'safe' attributes of the 'slave' model and use them as own attributes.
Thus you can use any attribute, which is marked as 'safe' in related ActiveRecord model in the scope
of this class. For example:

namespace app\models;

// ActiveRecord to be searched:
class Item extends \yii\db\ActiveRecord
{
    public function rules()
    {
        return [
            [['name', 'status', 'price'], 'required'],
            ['name', 'string'],
            ['status', 'integer'],
            ['price', 'number'],
        ];
    }
}

use yii2tech\ar\search\ActiveSearchModel;

// Create search model for declared ActiveRecord:
$searchModel = new ActiveSearchModel([
    'model' => 'app\models\Item'
]);

// safe attributes of `Item` are inherited:
$searchModel->name = 'Paul';
$searchModel->price = 10.5;

Inherited attributes may be used while composing web forms, which should collect filter data.
For example:

<?php
use yii2tech\ar\search\ActiveSearchModel;
use yii\widgets\ActiveForm;

$searchModel = new ActiveSearchModel([
    'model' => 'app\models\Item'
]);
?>
<?php $form = ActiveForm::begin(); ?>

<?= $form->field($model, 'name')->textInput() ?>
<?= $form->field($model, 'price')->textInput() ?>
...

<?php ActiveForm::end(); ?>

Attribute labels and hints are also inherited from the 'slave' model.

The main method of is search(). It loads filter attributes
from given data array, validates them an creates a instance applying
own attributes as a query filter condition.

ActiveSearchModel uses a sophisticated logic for the query filtering, based on the attribute types,
specified by , which value is extracted
from by default and filter operators list, specified via
.
By default will be used for the filter composition. For the
'string' attributes it will be used with 'like' operator. For 'integer' and 'float' ('double') method
andFilterCompare() will be used, if it is available.

Heads up! Do not abuse ActiveSearchModel usage. It has been designed to cover only the simplest
cases, when search logic is trivial. You should always create a separated search model in case, it
requires complex logic of composition of the search query.

Adjusting Data Provider

You may want to change some settings of the data provider, created by the search() method: change
pagination or sort settings and so on. You can do this via .
For example:

use yii2tech\ar\search\ActiveSearchModel;

$searchModel = new ActiveSearchModel([
    'model' => 'app\models\Item',
    'dataProvider' => [
        'class' => 'yii\data\ActiveDataProvider',
        'pagination' => [
            'defaultPageSize' => 40
        ],
    ],
]);
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
echo $dataProvider->pagination->defaultPageSize; // outputs `40`

Adjusting Search Query

You may use event to adjust the search query instance
adding relation eager loading or permanent conditions. For example:

use yii2tech\ar\search\ActiveSearchModel;
use yii2tech\ar\search\ActiveSearchEvent;

$searchModel = new ActiveSearchModel([
    'model' => 'app\models\Item',
]);
$searchModel->on(ActiveSearchModel::EVENT_AFTER_CREATE_QUERY, function(ActiveSearchEvent $event) {
    $event->query
        ->with(['category'])
        ->andWhere(['status' => 1]);
});

You may also specify query object directly via . For example:

use yii2tech\ar\search\ActiveSearchModel;
use yii\data\ActiveDataProvider;
use app\models\Item;

$searchModel = new ActiveSearchModel([
    'model' => Item::className(),
    'dataProvider' => function () {
        $query = Item::find()
            ->with(['category'])
            ->andWhere(['status' => 1]);

        return ActiveDataProvider(['query' => $query]);
    },
]);

Filter Operators

You can control the operators to be used for the query filtering via .
It defines a mapping between the attribute type and the operator to be used with .
Each value can be a scalar operator name or a PHP callback, accepting query instance, attribute name and value.
For example:

use yii2tech\ar\search\ActiveSearchModel;

$searchModel = new ActiveSearchModel([
    'model' => 'app\models\Item',
    'filterOperators' => [
        ActiveSearchModel::TYPE_STRING => '=', // use strict comparison for the string attributes
        ActiveSearchModel::TYPE_INTEGER => function (\yii\db\ActiveQueryInterface $query, $attribute, $value) {
            if ($attribute === 'commentsCount') {
                $query->andHaving(['commentsCount' => $value]);
            } else {
                $query->andFilterWhere([$attribute => $value]);
            }
        },
    ],
]);

ActiveSearchModel allows filtering for the attributes using andFilterCompare() method of the query (for example:
), which allows specifying filter value in format: {operator}{value} (for
example: >10, <=100 and so on). The list of attribute names, for which usage of such comparison is allowed is controlled
by . For example:

use yii2tech\ar\search\ActiveSearchModel;

$searchModel = new ActiveSearchModel([
    'model' => 'app\models\Item',
    'compareAllowedAttributes' => [
        'price' // allow compare for 'price' only, excluding such fields like 'categoryId', 'status' and so on.
    ],
]);

You can set compareAllowedAttributes to *, which indicates any float or integer attribute will be allowed for comparison.

Note: take precedence over .

Working Without 'Slave' Model

Although in most cases setup of is a quickest way to configure ActiveSearchModel
instance, it is not mandatory. You can avoid setup of the 'slave' model and configure all search related properties
directly. For example:

use yii2tech\ar\search\ActiveSearchModel;
use yii\data\ActiveDataProvider;
use app\models\Item;

$searchModel = new ActiveSearchModel([
    'searchAttributeTypes' => [
        'id' => ActiveSearchModel::TYPE_INTEGER,
        'name' => ActiveSearchModel::TYPE_STRING,
        'price' => ActiveSearchModel::TYPE_FLOAT,
    ],
    'rules' => [
        ['id', 'integer'],
        ['name', 'string'],
        ['price', 'number'],
    ],
    'compareAllowedAttributes' => [],
    'dataProvider' => function () {
        $query = Item::find()
            ->with(['category'])
            ->andWhere(['status' => 1]);

        return ActiveDataProvider(['query' => $query]);
    },
]);

主要指标

概览
名称与所有者netlify/staticgen
主编程语言JavaScript
编程语言PHP (语言数: 1)
平台
许可证MIT License
所有者活动
创建于2014-04-25 19:15:38
推送于2020-10-20 17:30:12
最后一次提交2020-10-20 13:30:11
发布数0
用户参与
星数2.5k
关注者数95
派生数552
提交数1.2k
已启用问题?
问题数92
打开的问题数19
拉请求数643
打开的拉请求数0
关闭的拉请求数179
项目设置
已启用Wiki?
已存档?
是复刻?
已锁定?
是镜像?
是私有?