悠悠楠杉
网站页面
正文:
在Laravel开发中,我们经常遇到需要全局过滤数据的场景,比如多租户系统的租户隔离、软删除数据的自动隐藏,或是业务状态的条件筛选。这时候,全局作用域(Global Scopes)就像一把瑞士军刀,能优雅地统一处理这些需求,避免在每个查询中重复编写相同逻辑。
全局作用域是Laravel Eloquent提供的一种机制,允许开发者强制为所有模型查询添加约束条件。与局部作用域不同,它不需要手动调用,而是自动生效,类似一个“隐形的WHERE子句”。
deleted_at不为空的记录tenant_id = current_tenant条件status = 'published'的活跃数据适用于简单逻辑,直接在模型booted方法中定义:
protected static function booted()
{
static::addGlobalScope('active', function (Builder $builder) {
$builder->where('status', 'active');
});
}创建独立的Scope类,实现apply方法:
namespace App\Models\Scopes;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Scope;
class TenantScope implements Scope
{
public function apply(Builder $builder, Model $model)
{
$builder->where('tenant_id', auth()->user()->tenant_id);
}
}在模型中注册:
protected static function booted()
{
static::addGlobalScope(new TenantScope());
}User::withoutGlobalScope(TenantScope::class)->get();static::addGlobalScope('first', new FirstScope());
static::addGlobalScope('second', new SecondScope());通过合理使用全局作用域,你可以将分散在各处的数据过滤逻辑集中管理,使代码更符合DRY原则。当项目规模扩大时,这种规范化的数据层约束会显著提升系统的可维护性。