2014-02-14 34 views
1

對於Laravel,命名空間和類我還是比較新的。我有一個應用程序特定的類,它自動加載正確,並有它自己的名稱空間。這個類擴展了雄辯。Laravel擴展Eloquent

我想要做的是找到方法來優化我的代碼。這裏是一個樣本:

$collection = Collection::where('user_id', '=', Auth::user()->id)->with('photos')->get(); 

所以我有一個集合模型,它擴展了我自己的Appspecific抽象類。上面的代碼沒有什麼不對,但是我會做很多事情,我很樂意爲了可讀性對它進行優化。事情是這樣的:

$collection = Collection::getMine()->with('photos')->get(); 
在我的應用程序特定的類

現在我有這樣的:

public static function getMine() { 
    if(\Auth::guest()) 
     return false; 

    return $this->where('user_id', '=', \Auth::user()->id); //would not work coz im not in object context 

} 

我在做什麼錯?我在正確的課上做這個嗎?我應該在另一個擴展其他類的類上做這個,請說BuilderClass?

回答

3

您正在尋找Eloquent's scope methods

public function scopeGetMine ($query) 
{ 
    if(\Auth::guest()) return false; 

    return $query->where('user_id', \Auth::user()->id); 

} 

那麼就使用它,你想:

$collection = Collection::getMine()->with('photos')->get();