n7olkachev/laravel-filterable

为您的模型提供简洁的作用域

v2.0.0 2017-08-25 23:06 UTC

This package is auto-updated.

Last update: 2024-09-23 21:24:16 UTC


README

Code quality Licence Build Status

为什么?

这个包由标准的 Laravel 作用域驱动,而不是其他类似的包,它将类似 Filter 类的东西引入到您的代码中,因此更容易上手。此外,如果您决定从项目中移除此包,您仍将保留可以直接使用的标准作用域。

我个人使用这个特质来加快开发速度,将其与 $request->all() 结合使用。

Page::filter($request->all())->get()

默认情况下,您将获得等值过滤器(where field = bar),如果您需要支持其他查询,只需添加新的作用域即可,无需更改除了模型之外的内容。请参见示例以获得更好的理解。

示例

class Page extends Model
{
    use Filterable;

    protected $fillable = [
        'title',
        'status',
        'created_at',
    ];
    
    protected $filterable = [
        'title',
        'created_after'
    ];

    public function scopeCreatedAfter($query, $time)
    {
        return $query->where('created_at', '>', $time);
    }
}

现在,我们可以使用 filter 作用域来过滤我们的查询

Page::filter(['title' => 'Cool page'])->first(); // equals to where('title', 'Cool page')

Page::filter(['status' => ['new', 'active'])->get() // equals to whereIn('status', ['new', 'active'])

Page::filter(['created_after' => '2017-01-01'])->get() // equals to createdAfter('2017-01-01') (notice our scope in Page class)

当然它支持具有多个键的过滤器

Page::filter(['title' => 'Cool page', 'status' => 'active'])->first()

安装

您可以通过 composer 安装此包

composer require n7olkachev/laravel-filterable

接下来,添加 Filterable 特质并列出所有可过滤属性

use Filterable;

protected $filterable = ['created_at', 'title'];

这就完了!

测试

$ composer test

致谢

赞助商

https://websecret.by/

位于白俄罗斯明斯克的一家网络机构

许可证

MIT 许可证 (MIT)