最近在开发一个项目
比如很简单的每个管理员登录后只管理自己的文章
就是文章表有一个字段是admin_id
这样在相关的查询更新及删除操作为了安全起见都要加上where admin_id='$admin_id`
感觉好麻烦
在laravel中有全局作用域,只需要在Model中定义即可使用
是指在模型类中预设过滤器,在模型类的所有查询中都生效。
通过全局作用域类实现
编写一个实现IlluminateDatabaseEloquentScope 接口的全局作用域类,这里我们将其命名为 EmailVerifiedAtScope,并将其放到 app/Scopes
目录下:
<?php
namespace App\Scopes;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Scope;
class EmailVerifiedAtScope implements Scope
{
public function apply(Builder $builder, Model $model)
{
return $builder->whereNotNull('email_verified_at');
}
}
将全局作用域类注册到User模型,这样在User模型上进行查询的时候才可以应用相应的过滤条件。重写该模型父类的boot方法
protected static function boot()
{
parent::boot();
static::addGlobalScope(new EmailVerifiedAtScope());
}
通过匿名函数实现
在模型类的boot方法中通过匿名函数实现全局作用域:
protected static function boot()
{
parent::boot();
static::addGlobalScope('email_verified_at_scope', function (Builder $builder) {
return $builder->whereNoNull('email_verified_at');
});
}
移除全局作用域
User::withoutGlobalScope(EmailVerifiedAtScope::class)->get(); # 指定类
User::withoutGlobalScope('email_verified_at_scope')->get(); # 匿名函数
User::withoutGlobalScopes()->get(); # 移除所有全局作用域
User::withoutGlobalScopes([FirstScope::class, SecondScope::class])->get(); # 移除多个类/匿名函数
如有问题,可以QQ搜索群1028468525加入群聊,欢迎一起研究技术
转载请注明:laravel模型中查询全局作用域 出自老鄢博客 | 欢迎分享