ar-search

Provides unified search model for Yii ActiveRecord

Github stars Tracking Chart

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]);
    },
]);

Main metrics

Overview
Name With Ownernetlify/staticgen
Primary LanguageJavaScript
Program languagePHP (Language Count: 1)
Platform
License:MIT License
所有者活动
Created At2014-04-25 19:15:38
Pushed At2020-10-20 17:30:12
Last Commit At2020-10-20 13:30:11
Release Count0
用户参与
Stargazers Count2.5k
Watchers Count95
Fork Count552
Commits Count1.2k
Has Issues Enabled
Issues Count92
Issue Open Count19
Pull Requests Count643
Pull Requests Open Count0
Pull Requests Close Count179
项目设置
Has Wiki Enabled
Is Archived
Is Fork
Is Locked
Is Mirror
Is Private