从请求中添加自动搜索

安装: 85

依赖项: 0

建议者: 0

安全: 0

星标: 7

关注者: 2

分支: 0

开放问题: 5

类型:laravel

v1.0.4 2023-12-13 13:34 UTC

This package is auto-updated.

Last update: 2024-09-13 15:24:25 UTC


README

此包允许您仅使用查询字符串创建简单的搜索查询。

安装

只需运行以下命令

composer require aminsamadzadeh/simorgh

用法

当您想要搜索某些内容时,可以在控制器中使用此包。第一次使用时,必须在您想要搜索的模型中添加此包。

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use AminSamadzadeh\Simorgh\Filterable;

class User extends Model
{
    use Filterable;
}

如果您只想搜索特定字段,必须在模型中添加 $filterable

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use AminSamadzadeh\Simorgh\Filterable;

class User extends Model
{
    use Filterable;
    protected $filterable = ['name', 'email'];
}

在控制器中,您可以使用此功能。

<?php
namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use App\User;

class UserController extends Controller
{

    public function index()
    {
    	$users = User::filter(request()->all())->get();
        return view('users.index', compact('users'));
    }

}

查询

简单条件

带有simorgh的请求查询字符串

/users?filter[name]=amin

没有simorgh的Eloquent查询

$users = User::where('name', 'amin')->get();

SQL原始查询

select * from "users" where "name" = 'amin'

关系型

带有simorgh的请求查询字符串

/articles?filter[images.id]=1

没有simorgh的Eloquent查询

$articles = Article::whereHas('images',function ($q) {
                $q->where($id, 1);
            }
        );

SQL原始查询

select * from "articles" where exists (select * from "images" where "articles"."id" = "images"."article_id" and "id" = 1)

范围(介于...之间)

带有simorgh的请求查询字符串

/users?filter[created_at]=(1970-01-01,1970-02-01)

没有simorgh的Eloquent查询

$users = User::whereBetween('created_at', ['1970-01-01', '1970-02-01'])->get();

SQL原始查询

select * from "users" where "created_at" between 1970-01-01 and 1970-02-01

数组

带有simorgh的请求查询字符串

/users?filter[id][]=1&filter[id][]=2&filter[id][]=3

没有simorgh的Eloquent查询

$users = User::where('id', [1,2,3])->get();

SQL原始查询

select * from "users" where "id" in (1, 2, 3)

排序

带有simorgh的请求查询字符串

/users?filter[sort]=created_at&filter-meta[sort-order]=desc

没有simorgh的Eloquent查询

$users = User::orderBy('created_at', 'desc')->get();

SQL原始查询

select * from "users" order by "created_at" desc

设置

元数据

要更改查询运算符,可以在查询字符串中使用元数据。

https://host.com/users?filter[name]=amin?filter-meta[name][op]=like

在模型中设置默认元数据

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use AminSamadzadeh\Simorgh\Filterable;

class User extends Model
{
    use Filterable;
    protected $filterable = ['name', 'email'];
    protected $filterMeta = ['name' => ['op' => 'like']];
}

注意:支持运算符 like=

查询字符串名称的别名(过滤和过滤元数据)

如果想要更改过滤和过滤元数据查询字符串的名称,可以在模型中添加更改后的名称。

.
.
.

class User extends Model
{
    use Filterable;
    protected $filter_name = 'f';
    protected $filter_meta = 'fm';

}