2016-02-01 20 views
1

爲了避免重複的代碼,我想在我的雄辯模型中創建一個函數eagerLoading()。這裏是我的代碼:在我的口才對象中設置一個熱切的加載函數

型號產品

public function scopeActive($query) 
{ 
    return $query->where('active', 1); 
} 

public function eagerLoading($query) 
{ 
    return $query->with([ 
     'owners', 
     'attributes', 
     'prices' => function ($query) 
     { 
      $query->orderBy('created_at', 'desc'); 
      $query->distinct('type'); 
     } 
    ]); 
} 

myController的

$products = Product::active()->eagerLoading()->paginate(100); 
return $this->response->withPaginator($products, $this->productTransformer); 

但是使用這個的時候,我有這樣的錯誤:Call to undefined method Illuminate\Database\Query\Builder::eagerLoading()

我該如何使用我的功能?

+2

嘗試將其重命名爲scopeEagerLoading,即可。 –

回答

1

eagerLoading()方法僅僅是另一個範疇,像你scopeActive()方法。爲了做你想做的事,你需要將它重命名爲scopeEagerLoading()

現在,Product::active()正在返回一個Eloquent查詢生成器。然後你試圖撥打eagerLoading(),該方法不存在。通過在scope前加上方法,它會通知查詢構建器調用它所查詢的模型上的方法。

1

從文檔:
「要定義一個作用域,只需在作用域前面插入一個Eloquent模型方法即可。」

檢查文檔:https://laravel.com/docs/5.1/eloquent#query-scopes

所以,你需要重命名你的方法有「範圍」開頭。

變化public function eagerLoading($query)public function scopeEagerLoading($query)

相關問題