2015-04-05 131 views
3

我試圖按鏈接的表計數排序查詢,無法弄清楚如何使用Laravel分頁;下面是我的查詢傳遞到視圖Laravel 5,分頁和排序的關係計數列表

我認爲Laravel 5 paginator方法已被移動?

$companies = Company::with('locations')->get()->sortBy(function($count) 
    { 
     return $count->locations->where('status', '=', 'Active')->count(); 
    }, null, true); 

因爲get和sortby函數被調用,我不能適用分頁(以下錯誤)

調用未定義的方法照亮\數據庫\雄辯\收藏::分頁()

也許有一種替代方法可以通過計算hasMany關係進行排序 - 在本例中爲「locations」。 (側面問題;我不知道如何使用hasManyThrough關係來完成上述工作)。

模型關係如下圖所示

public function locations() 
{ 
    return $this->hasMany('App\Location'); 
} 

public function equipment() 
{ 
    return $this->hasManyThrough('App\Equipment', 'App\Location'); 
} 

使用類似下面給出了一個不確定的「做」的方法?

return Paginator::make($companies->all(), $companies->getTotal(), $companies->getPerPage()) 
+0

我在這發現的最佳參考是; https://laracasts.com/forum/?p=1715-filtering-pagination-result/0,但我無法讓它工作! – 2015-04-06 01:11:40

+0

可能的[laravel 4 paginate collection]的副本(http://stackoverflow.com/questions/15233667/laravel-4-paginate-collection) – Anthony 2015-04-06 01:34:25

+0

這是laravel 5;我認爲自4以來分頁已經發生了顯着變化? – 2015-04-06 05:39:51

回答

1

這裏是我的編輯答案,那種通過命令和分頁確實可以一起工作,下面應該爲你工作,當然你可能需要調整的範圍列連接語句。

將此功能添加到您的公司類。

public function scopeLocationCount($query){ 
    return $query->join('locations','locations.company_id','=','companies.id') 
      ->selectRaw('companies.*, count(locations.id) as count')->where('locations.status','=','active')->groupBy('companies.id'); 
} 

然後你可以打電話給paginate方法就像這樣。

$companies= (Company::with('locations')->locationCount()->orderBy('count')->paginate(30)); 

然後你寫你的foreach循環來顯示你需要渲染,像這樣的{!! $companies->render() !!}的分頁程序後的細節。

希望這會有所幫助。

+0

如果我按照你的建議去做;每個頁面將按計數排序 - 我希望整個集合按計數排序。 – 2015-04-14 09:34:10

+0

然後在sortBy之後將paginate調用移動到最後。 – Azeame 2015-04-14 10:14:31

+0

分頁方法在sortby集合上不起作用 – 2015-04-14 11:50:04