PHPackages                             wyzheng/search-model - 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. wyzheng/search-model

ActiveLibrary

wyzheng/search-model
====================

扩展 laravel 的 ORM 使其具有简单的搜索功能。

v1.0.1(1y ago)51.0kMITPHPPHP ^8.0

Since Aug 28Pushed 1y ago1 watchersCompare

[ Source](https://github.com/wyzheng1997/search-model)[ Packagist](https://packagist.org/packages/wyzheng/search-model)[ RSS](/packages/wyzheng-search-model/feed)WikiDiscussions main Synced 1mo ago

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

扩展laravel ORM，使其拥有快速处理查询请求的能力。
------------------------------

[](#扩展laravel-orm使其拥有快速处理查询请求的能力)

安装
--

[](#安装)

```
composer require wyzheng/search-model
```

使用
--

[](#使用)

目前支持的查询类型有：`like`, `=`, `>`, `=`, ` 'like', // 声明数据库title字段模糊搜索
    'category_id' => '=', // 声明数据库category_id字段精确搜索
    'created_at' => 'between' // 支持get数组参数或开始和结束用逗号隔开的形式
    'user_id' => 'in' // 支持get数组参数或逗号隔开的形式
])->get();
```

### 自定义请求参数

[](#自定义请求参数)

当数据库字段和请求字段不同时，可以显式声明请求字段名

```
// https://example.com/api/articles?text=test&cate_id=5
$articles = Article::search([
    'title' => ['like', 'text'],
    'category_id' => ['=', 'cate_id'],
])->get();
```

### 跨表查询

[](#跨表查询)

当查询的字段是关联表的字段时，可以使用`.`的方式指定

```
// https://example.com/api/articles?title=test&author_name=jack
$articles = Article::search([
    'title' => 'like',

    // 当没有显式声明请求字段时，会自动拼接author_name
    // 支持无限层级关联 author.company.name, 默认值 $request->input('author_company_name')
    'author.name' => '=',
])->get();

```

### 自定义查询

[](#自定义查询)

可以通过自定义查询方法来实现更复杂的查询

```
// https://example.com/api/articles?title=test&type=1,2
$articles = Article::search([
    'title' => 'like',

    // $value = $request->input('type');
    'type' => fn ($query, $value) => $query->whereNotIn('type', explode(',', $value)),
])->get();
```

同时也支持自定义宏，此扩展包目前内置了一个处理时间区间查询的宏`whereBetweenDate`，可以直接使用

```
// 自定义宏示例（已内置，可直接使用）
Builder::macro('whereBetweenDate', function(string $filed, $input) {
    [$startDate,$endDate] = is_array($input) ? $input : explode(',', $input);
    return $this->whereDate($filed, '>=', $startDate)
        ->whereDate($filed, '
