首页 > 解决方案 > 在特定查询上避免 laravel 全局范围

问题描述

我有一个stuents有 3 列的表格graduatedleaver并且deleted_at.

graduate 和 leaver 是 int (1),默认值为 null。当学生毕业或离开学校时,对应的列变为 1。

当我使用

$students=Student::get();

我只需要返回 Student where graduatedand leaverare 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();

标签: phplaraveleloquent

解决方案


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

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

我会在您的模型中创建一个名为graduatedand的本地范围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

推荐阅读