[英]How to use pagination in laravel 5 with Raw query
我有一個簡單的問題,我找不到我需要的東西。
我需要計算商店列表的t2地理編碼點之間的距離。 我還需要將它分頁為WebService。
這有效,但結果中沒有距離:
public function stores(){
return Store::paginate(10);
}
結果是:
{
total: 4661,
per_page: 10,
current_page: 6,
last_page: 467,
next_page_url: "WS_URL/stores/?page=7",
prev_page_url: "WS_URL/stores/?page=5", from: 51,
to: 60,
data: [ {
id: "51",
name: "Sprouts",
.
.
lng: "-118.359688",
lat: "33.808281",
country: "usa"
},
.
.
.
]}
但我需要這個代碼工作:
public function stores(){
return DB::table('stores')
->selectRaw(' *, distance(lat, ?, lng, ?) as distance ')
->setBindings([ 41.123401,1.2409893])
->orderBy('distance')
->paginate($this->limit);
}
這就是結果:
{total: 0,
per_page: 10,
current_page: 1,
last_page: 0,
next_page_url: null,
prev_page_url: null,
from: 1,
to: 10,
data: [{
id: "3686",
name: "Bon Area",
.
.
lng: "1.602016",
lat: "41.266823",
distance: "0.15091"
},
.
.
.
]
}
我需要next_page_url
和prev_page_url
有任何想法嗎?
在selectRaw
模型上使用selectRaw
方法。
Store::selectRaw('*, distance(lat, ?, lng, ?) as distance', [$lat, $lon])
->orderBy('distance')
->paginate(10);
在這種情況下,Laravel會向數據庫詢問行數(使用select count(*) as aggregate from stores
),這樣可以節省RAM。
好的,我有一個解決方案! 我不喜歡它,因為我必須加載RAM中的所有行,然后使用手動分頁器。
public function stores($lat, $lon){
$stores = DB::table('stores')
->selectRaw(' *, distance(lat, ?, lng, ?) as distance ')
->setBindings([$lat,$lon])
->orderBy('distance')
->get();
$result_p = new Paginator($stores, $this->limit, Request::input('page'),['path' => Request::url() ]);
return $result_p;
}
在此之后我看起來更加信息,問題是setBindings([$ lat,$ lon])
最新和良好的解決方案:
public function stores($lat, $lon){
return $stores = DB::table('stores')
->selectRaw(" *, distance(lat, {$lat}, lng, {$lon}) as distance ")
->orderBy('distance')
->paginate($this->limit);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.