php - 在特定查询上避免 laravel 全局范围
问题描述
我有一个stuents
有 3 列的表格graduated
,leaver
并且deleted_at
.
graduate 和 leaver 是 int (1),默认值为 null。当学生毕业或离开学校时,对应的列变为 1。
当我使用
$students=Student::get();
我只需要返回 Student where graduated
and leaver
are 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();
解决方案
如果您需要在特定查询中避免全局范围,yuu 应该使用withoutGlobalScope
:
Students::withoutGlobalScope('onlyGraduated')->where("graduated",1)->get();
我会在您的模型中创建一个名为graduated
and的本地范围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
推荐阅读
- c++ - 我怎样才能拥有一个以二维数组作为参数的函数,而该数组有一个我想要更改的参数/维度?
- python - 如何从检索到的 JSON 数据中删除双引号
- aws-lambda - spacy with zappa 在 AWS lambda 上显示错误
- c++ - 无法在 Visual Studio Code 中构建 c++
- excel - 根据单元格值将图像从子目录插入 Excel
- c++ - 满足以下条件的高效图算法?
- python - 如何为性别写一个布尔值并取平均值
- sharepoint - 重复部分的非重复部分
- bash - 如何使用awk或any在命令行中为长行列表打印每组的最后一行?
- android - 添加三个或更多 CustomAttribute 元素时,MotionLayout 抛出 ArrayIndexOutOfBoundsException