php 局部和全局作用域,Laravel 使用全局作用域和局部作用域进行查询

全局作用域

是指在模型类中预设过滤器,在模型类的所有查询中都生效。

通过全局作用域类实现

编写一个实现Illuminate\Database\Eloquent\Scope 接口的全局作用域类,这里我们将其命名为 EmailVerifiedAtScope,并将其放到 app/Scopes 目录下:

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(); # 移除多个类/匿名函数

局部作用域

局部作用域在模型类中定义,该方法需要以scope开头。

public function scopePopular(Builder $query)

{

return $query->where('views','>',0)->orderBy('views','desc');

}

使用:只需调用scope之后的过滤器名称即可。

$post = Post::popular()->get();

动态作用域

动态作用域和局部作用域类似,只不过可以通过额外参数指定查询条件。

public function scopeOfType(Builder $query, $type)

{

return $query->where('type', $type);

}

标签:Laravel,function,get,作用域,boot,User,全局

来源: https://www.cnblogs.com/bigcola/p/13388390.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值