为了账号安全,请及时绑定邮箱和手机立即绑定

避免特定查询上的 laravel 全局作用域

避免特定查询上的 laravel 全局作用域

PHP
不负相思意 2023-11-03 15:15:18
我有一个stuents包含 3 列的表格graduated,leaver并且deleted_at。毕业和离开者都是 int (1),默认值为 null。当学生毕业或离开学校时,相应的栏位变为1。当我使用$students=Student::get();我只需要返回 Student(其中graduated和leaver为 null),因此我创建了两个全局范围:protected static function boot(){    parent::boot();     static::addGlobalScope('onlyGraduated', function ($builder) {        $builder->where('graduated', null);    });    static::addGlobalScope('onlyLeaver', function ($builder) {        $builder->where('leaver', null);    }); }这适用于大多数用例,但是当我希望学生毕业时,我应该对某些特定查询做什么?例如Students::where("graduated",1)->get();
查看完整描述

1 回答

?
慕尼黑5688855

TA贡献1848条经验 获得超2个赞

如果您需要避免特定查询中的全局范围,则 yuu 应使用withoutGlobalScope:


Students::withoutGlobalScope('onlyGraduated')->where("graduated",1)->get();

我将在您的模型中创建一个名为graduated和 的本地范围leaver:


public function scopeGraduated($query) {

  return $query->withoutGlobalScope('onlyGraduated')->where("graduated",1);

}


public function scopeLeavers($query) {

  return $query->withoutGlobalScope('onlyLeaver')->where("leaver",1);

}

然后您将能够使用以下方式查询数据:


Students::get(); // Only students with both graduated and leaver null

Students::graduated()->get(); // Students with leaver null and graduated 1

Students::leavers()->get(); // Students with leaver 1 and graduated null


查看完整回答
反对 回复 2023-11-03
  • 1 回答
  • 0 关注
  • 59 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信