我错过了在Laravel5.5中全球范围是如何工作的。
在我的控制器index
中,我将过滤器传递到一个getter中:
public function index(SaleFilters $filters)
{
return new SaleCollection($this->getSales($filters));
}
getSales
protected function getSales(SaleFilters $filters)
{
$sales = Sale::with('office')->filter($filters);
return $sales->paginate(50);
}
protected function range($range)
{
$dates = explode(" ", $range);
if (count($dates) == 2) {
$this->builder = Sale::with(['office', 'staff'])
->where('sale_date', '>=', $dates[0])
->where('sale_date', '<', $dates[1])
->orderBy('sale_date', 'desc');
return $this->builder;
}
return false;
}
我在sale
模型中有一个作用域设置,我认为它会自动应用到上面的过滤器中?如果没有,是否必须重新应用相同的作用域,在筛选器中复制作用域代码?
protected static function boot()
{
parent::boot();
$user = Auth::user();
if (($user) && ($user['office_id'])) {
return Sale::ofOffice($user['office_id'])->get();
}
}
public function scopeOfOffice($query, $office)
{
return $query->where('office_id', $office);
}
因此,基本上,如果用户应用了office_id
,它应该应用ofOffice
作用域,因此它应该只返回应用于该office_id
的销售。
基本上,它通过axios请求在页面加载上工作。
Route::get('/sales', 'SalesController@index')->middleware('auth:api');
axios
.get('api/sales/?range=" + this.rangeFilter)
rangeFilter
基本上是传递给上述筛选器查询的开始和结束日期。
有人能解释一下范围是如何工作的吗?或者,如果有什么明显的事情,为什么它不总是工作的?正如我说过的,它在页面加载中工作,我为rangeFilter
提供了默认值,但是当我更改那些日子,并且它通过相同的axios调用重新获取时,它似乎没有应用这个范围,我得到了所有的结果,而不是where office_id = 'x'
。
就我而言,上面的范围筛选器也会在第一个页面加载时执行,所以不确定为什么会在那里应用,而不是以后。
发布于 2017-12-04 04:19:57
不应将动态作用域的使用与全局范围的使用混为一谈。此外,静态boot
函数不期望返回。为了使用动态范围,每次需要时都需要调用它。因此,名称是动态的。默认情况下,并不总是执行应用的查询。在那里如此,
protected function getSales(SaleFilters $filters)
{
$sales = Sale::ofOffice($anyOfficeHere)->with('office')->filter($filters);
return $sales->paginate(50);
}
为了适应现有代码,您可能需要在模型中添加一个if
语句。然后在没有参数的情况下调用作用域函数。
public function scopeOfOffice($q)
{
if (($user = \Auth::user()) && ($office = $user->office_id)) {
$q->where('office_id', $office);
}
}
// Your controller
protected function getSales(SaleFilters $filters)
{
$sales = Sale::ofOffice()->with('office')->filter($filters);
return $sales->paginate(50);
}
如果您觉得重复输入ofOffice
非常麻烦的话。全球范围是可行的。在您的模型静态boot
函数中,如果您感到在应用程序中创建了一个独立的类,您也可以应用匿名函数。
protected static function boot()
{
parent::boot();
static::addGlobalScope('officeOrWhatNot', function ($q) {
if (($user = \Auth::user()) && ($office = $user->office_id)) {
$q->where('office_id', $office);
}
});
}
// Your controller. No more `ofOffice`, it's automatically applied.
protected function getSales(SaleFilters $filters)
{
$sales = Sale::with('office')->filter($filters);
return $sales->paginate(50);
}
https://stackoverflow.com/questions/47632272
复制相似问题