能否为模型指定默认where条件,所有查询自动追加该条件?
实现方案
可以直接使用Laravel框架内置的全局作用域(Global Scope) 特性实现该需求,无需自定义公共查询方法或每次手动拼接条件,具体配置如下:
方案1:单模型使用(最简便)
直接在TestModal模型类中重写boot方法,注册匿名全局作用域即可:
<?php namespace App\Models; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Builder; class TestModal extends Model { protected static function boot() { parent::boot(); // 注册全局默认查询条件 static::addGlobalScope('filter_type_r', function (Builder $query) { $query->where('type', 'r'); // 如果你希望该条件仅对select查询生效,不对更新/删除操作生效,可以替换为下面的写法 // if (!$query->getQuery()->isWriteType()) { // $query->where('type', 'r'); // } }); } }
配置完成后所有针对TestModal的查询都会自动追加type = 'r'的条件:
- 你原有代码
$var = TestModal::where('date', '2021-06-08')->get();执行时,实际运行的SQL会自动拼接条件,等价于手动写了TestModal::where('type', 'r')->where('date', '2021-06-08')->get(); - 关联查询、聚合查询等所有读操作都会自动生效
临时取消默认条件的方法
如果有特殊场景需要跳过这个默认条件,调用withoutGlobalScope方法即可:
// 仅移除type筛选的全局条件 $allData = TestModal::withoutGlobalScope('filter_type_r')->get(); // 移除所有全局条件(包括软删除等框架内置全局条件) $allData = TestModal::withoutGlobalScopes()->get();
方案2:多模型复用
如果有多个模型都需要追加相同的type = 'r'条件,可以把逻辑抽成独立的作用域类,避免重复代码:
- 新建作用域类
app/Scopes/TypeRScope.php:
<?php namespace App\Scopes; use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Scope; class TypeRScope implements Scope { public function apply(Builder $query, Model $model) { $query->where('type', 'r'); } }
- 在需要生效的模型的
boot方法中注册:
use App\Scopes\TypeRScope; protected static function boot() { parent::boot(); static::addGlobalScope(new TypeRScope); }
内容的提问来源于stack exchange,提问作者Stackoverflower
相关产品推荐
相关产品推荐

