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

我有一个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();


不负相思意
浏览 64回答 1
1回答

慕尼黑5688855

如果您需要避免特定查询中的全局范围,则 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 nullStudents::graduated()->get(); // Students with leaver null and graduated 1Students::leavers()->get(); // Students with leaver 1 and graduated null
打开App,查看更多内容
随时随地看视频慕课网APP