PHP code example of wyzheng / search-model

1. Go to this page and download the library: Download wyzheng/search-model library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

wyzheng / search-model example snippets


// https://example.com/api/articles?title=test&category_id=5&created_at=2020-01-01,2021-01-02&user_id=1,2,3
$articles = Article::search([,
    'title' => '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();

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

// https://example.com/api/articles?created_at=2020-01-01,2021-01-02
$articles = Article::search([
    'created_at' => 'whereBetweenDate',
    // 同样也支持显式声明请求字段名
    // 'created_at' => ['whereBetweenDate', 'create_time']
])

$articles = Article::search([
    'title' => 'like', 
], ['author' => function($author) {
    $author->select('id', 'name');
}])->get();

// https://example.com/api/articles?title=test&sort_by=asc(id),desc(author_level)
$articles = Article::search([
    'title' => 'like', 
])->sort(['id', 'author_level' => function($query, $direction) {
    // $direction 取值 'asc' 或 'desc'
    $query->orderByRaw('.......')
}])->get();