You need to enable JavaScript to run this app. 如何在Laravel的Model中全局设置where查询条件?
优惠活动
大模型
产品
解决方案
定价
更多

如何在Laravel的Model中全局设置where查询条件?

实现方案

你需要的功能可以通过Laravel的**全局查询作用域(Global Scope)**实现,设置后所有对Staff模型的查询都会自动拼接active = 1的条件,无需在每个调用位置重复写,修改规则时只要调整作用域定义即可。

以下是两种常用实现方式:

方式1:匿名全局作用域(适合简单场景)

直接在Staff模型的booted方法中定义,实现快速:

// app/Models/Staff.php
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;

class Staff extends Model
{
    protected static function booted()
    {
        static::addGlobalScope('active', function (Builder $builder) {
            $builder->where('active', 1);
        });
    }
}

设置完成后,你直接调用Staff::get()就等价于原有的Staff::where('active',1)->get()。如果特殊场景需要查询包含未激活状态的员工数据,可以手动移除作用域:

Staff::withoutGlobalScope('active')->get();

方式2:独立作用域类(适合复杂/复用场景)

如果后续过滤规则会变复杂,或者其他模型也需要用到相同的激活状态过滤,可以单独定义作用域类:

  1. 新建作用域文件app/Scopes/ActiveScope.php:
// app/Scopes/ActiveScope.php
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Scope;

class ActiveScope implements Scope
{
    public function apply(Builder $builder, Model $model)
    {
        $builder->where('active', 1);
    }
}
  1. 在Staff模型中注册该作用域:
// app/Models/Staff.php
use App\Scopes\ActiveScope;
use Illuminate\Database\Eloquent\Model;

class Staff extends Model
{
    protected static function booted()
    {
        static::addGlobalScope(new ActiveScope);
    }
}

需要移除该作用域时调用:

Staff::withoutGlobalScope(ActiveScope::class)->get();

注意事项

  • 全局查询作用域仅对查询操作生效,update、delete等写操作不会自动拼接该条件
  • Laravel 8以下版本需将模型中的booted方法改为boot,其余逻辑完全一致

内容的提问来源于stack exchange,提问作者Bilal Arshad

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.20 06:15:03