我有一个简单的问题,但我没有找到我需要的。
我需要计算商店列表的 t2 个地理编码点之间的距离。我还需要它为 Web 服务分页。
这可行,但结果没有距离:
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
有什么想法吗?
最佳答案
在 Eloquent 模型上使用 selectRaw
方法。
Store::selectRaw('*, distance(lat, ?, lng, ?) as distance', [$lat, $lon])
->orderBy('distance')
->paginate(10);
在这种情况下,Laravel 会向数据库询问行数(使用 select count(*) as aggregate from stores
),这样可以节省您的 RAM。
关于php - 如何使用原始查询在 laravel 5 中使用分页,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30321497/