我有一个stuents
表格,其中有3列graduated
,leaver
和deleted_at
。
gradedd和leaver为int(1),默认值为null。当学生毕业或离开学校时,相应的列将变为1。
当我使用
$students=Student::get();
我只需要返回graduated
和leaver
为空的Student,因此我创建了两个全局范围:
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();
答案 0 :(得分:0)
如果您需要避免在特定查询中使用全局范围,则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