akr4m / scoping
此作用域允许您为给定模型的所有查询添加约束。轻松过滤数据。
v1.0.2
2021-10-25 20:57 UTC
Requires
- php: >=5.4.0
This package is auto-updated.
Last update: 2024-08-26 03:23:35 UTC
README
此作用域允许您为给定模型的所有查询添加约束。轻松过滤数据。
安装
只需将包添加到您的 composer.json
文件中,然后运行 composer update
。
composer require akr4m/scoping
使用方法
将特质添加到您的模型和搜索规则中。
use akr4m\scoping\Traits\CanBeScoped; class Post extends Model { use CanBeScoped; }
在 abcController.php
中添加作用域,如下所示
public function __invoke(Request $request) { $posts = App\Post::withScopes($this->scopes())->get(); } protected function scopes() { return [ // Must declare the `Scope` files 'topic' => new TopicScope(), 'month' => new MonthScope(), 'year' => new YearScope(), ]; }
TopicScope.php
文件将如下所示
use akr4m\scoping\Scoping\Contracts\Scope; use Illuminate\Database\Eloquent\Builder; class TopicScope implements Scope { public function apply(Builder $builder, $value) { return $builder ->whereHas('topics', function ($builder) use ($topic) { $builder->where('slug', $value); }); } }