PHPackages                             sndwow/yii2-rest-query-helper - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [API Development](/categories/api)
4. /
5. sndwow/yii2-rest-query-helper

ActiveYii2-extension[API Development](/categories/api)

sndwow/yii2-rest-query-helper
=============================

扩展yii2的rest功能，使其支持更多的参数

v1.0.1(8y ago)12446BSD-4-ClausePHP

Since Dec 13Pushed 8y ago1 watchersCompare

[ Source](https://github.com/sndwow/yii2-rest-query-helper)[ Packagist](https://packagist.org/packages/sndwow/yii2-rest-query-helper)[ RSS](/packages/sndwow-yii2-rest-query-helper/feed)WikiDiscussions master Synced 2d ago

READMEChangelog (1)Dependencies (1)Versions (3)Used By (0)

概述
--

[](#概述)

该扩展强化了Yii Restful查询。**支持无限级关联**

在关联查询数据时不是每次都回表查询，而是使用了with加载关联数据，由yii进行数据关系匹配，减少对数据库的访问。

```
例如查询所有user下的所有books，默认yii ar模型需要循环每个user，再调用user->books进行查询，要多次访问数据库。
而使用with急切加载，只需要查询2遍即可获得所有数据。

```

URL 参数支持
--------

[](#url-参数支持)

- 支持无限级关联搜索

url 关键字解释例子eq等于查询api.com?id=eq:1 等价于 api.com?id=1!eq不等于api.com?id=!eq:1，sql：id != 1like模糊查询api.com?name=like:数据 ，sql：%数据%llike左模糊查询api.com?name=llike:数据 ，sql：%数据rlike右模糊查询api.com?name=rlike:数据 ，sql：数据%nullNULL 查询api.com?name=null，sql： name IS NULL!nullNOT NULL 查询api.com?name=!null，sql： name IS NOT NULLless\_than小于查询api.com?age=less\_than:10，sql： age &lt; 10more\_than大于查询api.com?age=more\_than:10，sql： age &gt; 10less\_than\_eq小于等于查询api.com?age=less\_than\_eq:10，sql： age &lt;= 10more\_than\_eq大于等于查询api.com?age=more\_than\_eq:10，sql： age &gt;= 10in范围查询api.com?id=in:1,2,3，sql： id IN (1,2,3)!in排除范围查询api.com?id=！in:1,2,3，sql： id NOT IN (1,2,3)demo

```
// 查询id为1的用户，以及关联的模糊查询books.name
api.com/users?id=1,books.name=like:自然

```

- 支持无限级关联排序

url关键字 `_sort`

```
// user表id使用asc排序（不穿排序方式默认asc），books.name使用倒序，books.author.age倒序
api.com/users?id=1,books.name=like:自然&_sort=id,books.name.desc,books.author.age.desc

```

- 支持无限级字段过滤

url关键字 `_fields`

```
api.com/users?_fields=id,name,books.name,books.author.name

```

- 指定返回关联数据

url关键字 `_expand`

对应activeRecord内的relations。**以上所有关联查询必须先在此参数中设定，否则无法查询到关联数据**

例如需查询：books.name=like:自然，则必须先通过\_expand关联books

```
// 将返回关联的books，以及books内关联的author数据
api.com/users?_expand=books,books.author

```

控制层限制
-----

[](#控制层限制)

为了防止预期外的查询，可设置相应的规则进行查询限制。

场景：

某些字段不允许like查询，或者只允许某个字段排序（其他字段排序可能造成性能问题）

可通过设置规则，仅对符合规则的url参数进行查询。

```
public function actionIndex()
{
    ...
    $rules = [
        'where' => [
            'id' => '*', // 允许任意查询条件
            'name' => ['eq'], // 只允许等于查询
            'books.name'=>['like','in'] // 允许like查询和in查询
        ],
        // 只允许以下字段排序
        'sort' => [
            'id',
            'books.id'
        ]
    ];
    ...
}
```

安装
--

[](#安装)

建议通过 [composer](http://getcomposer.org/download/)安装

```
composer require sndwow/yii2-rest-query-helper

```

也可手动安装到：/vendor/sndwow/yii2-rest-query-helper

需要修改vendor/yiisoft/extensions.php，配置中追加

```
  'sndwow/yii2-rest-query-helper' =>
  array (
    'name' => 'sndwow/yii2-rest-query-helper',
    'version' => '1.0.1.0',
    'alias' =>
    array (
      '@sndwow/rest' => $vendorDir . '/sndwow/yii2-rest-query-helper',
    ),
  ),
```

使用
--

[](#使用)

- 所有关联 AR Model 需继承 sndwow\\rest\\ActiveRecord 使其强化关联能力
- 在控制器中指定 serializer 为 sndwow\\rest\\Serializer

```
class UserController extends \yii\rest\Controller
{
    public $serializer = 'sndwow\rest\Serializer';
    public function actionIndex()
    {
        // 仅在此方法指定
        // $this->serializer = 'sndwow\rest\Serializer';

        // 使用User作为主表，也可以使用类名：new QueryHelper('app\models\User')
        $helper = new QueryHelper(User::className())

        // 设置查询、排序规则
        $rules = [
            'where' => [
                'id' => '*', // 允许任意查询条件
                'name' => ['eq'], // 只允许等于查询
                'books.name'=>['like','in'] // 允许like查询和in查询
            ],
            // 只允许以下字段排序
            'sort' => [
                'id',
                'books.id'
            ]
        ];

        // 应用规则，并返回query实例
        // 实例与普通的query一样，只不过关联了相关数据，例如可以 $query->asArray()->all()
        $query = $helper->build($rules);

        // 使用此方式返回可以被sndwow\rest\Serializer进行处理
        // 同时也支持yii model 里的 fields，可自定义返回字段及数据
        return new ActiveDataProvider([
            'query' => $query
        ]);
    }
}
```

例子：

继承 yii\\rest\\ActiveController 用法

```
namespace app\modules\v1\controllers;

use app\modules\v1\models\Category;
use app\modules;
use sndwow\rest\QueryHelper;
use yii\data\ActiveDataProvider;
use yii\rest\ActiveController;

class CategoryController extends ActiveController
{
    public $modelClass = 'app\modules\v1\models\Category';

    public function actions()
    {
        $actions = parent::actions();
        unset($actions['index']);
        return $actions;
    }
    public function actionIndex()
    {
        $this->serializer = 'sndwow\rest\Serializer';
        $rules = [
            'sort' => [
                'id',
                'create_time',
                'items.markets.update_time'
            ],
            'where' => [
                'id' => '*',
                'name' => ['like', 'eq'],
                'items.name' => ['like'],
            ]
        ];
        $helper = new QueryHelper(Category::className());
        $query = $helper->build($rules);
        return new ActiveDataProvider([
            'query' => $query
        ]);
    }
}
```

继承 yii\\rest\\Controller 用法

```
namespace app\modules\v1\controllers;

use app\modules\v1\models\Category;
use app\modules;
use sndwow\rest\QueryHelper;
use yii\data\ActiveDataProvider;
use yii\rest\Controller;

class CategoryController extends Controller
{
    public $modelClass = 'app\modules\v1\models\Category';

    public function actionIndex()
    {
        $this->serializer = 'sndwow\rest\Serializer';
        $rules = [
            'sort' => [
                'id',
                'create_time',
                'items.markets.update_time'
            ],
            'where' => [
                'id' => '*',
                'name' => ['like', 'eq'],
                'items.name' => ['like'],
            ]
        ];
        $helper = new QueryHelper(Category::className());
        $query = $helper->build($rules);
        return new ActiveDataProvider([
            'query' => $query
        ]);
    }
}
```

###  Health Score

31

—

LowBetter than 68% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity18

Limited adoption so far

Community10

Small or concentrated contributor base

Maturity64

Established project with proven stability

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~0 days

Total

2

Last Release

3073d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/34fbb4d0ee285e89d3e983a54f0de0574ef1a0f5e7673b00b85e85a54c79f1d7?d=identicon)[sndwow](/maintainers/sndwow)

---

Top Contributors

[![sndwow](https://avatars.githubusercontent.com/u/18691029?v=4)](https://github.com/sndwow "sndwow (15 commits)")

---

Tags

yii2extension

### Embed Badge

![Health badge](/badges/sndwow-yii2-rest-query-helper/health.svg)

```
[![Health](https://phpackages.com/badges/sndwow-yii2-rest-query-helper/health.svg)](https://phpackages.com/packages/sndwow-yii2-rest-query-helper)
```

###  Alternatives

[dotzero/yii2-amocrm

Расширение для Yii Framework 2 реализующее клиент для работы с API amoCRM

1639.7k](/packages/dotzero-yii2-amocrm)[conquer/services

Yii2 soap wsdl web services

1632.5k](/packages/conquer-services)[apexwire/yii2-restclient

Tools to use API as ActiveRecord for Yii2

143.5k](/packages/apexwire-yii2-restclient)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
