我有个收藏品是靠:
$clinics = Clinic::orderBy('name', 'asc')->paginate(30)->withQueryString();假设这有多达5000项。
现在,我需要在foreach($clinics as $key => $clinic)循环中整理出那些距离用户输入的地址超过20公里的诊所。
然后我计算它是否在20公里之内,如果诊所在20公里以外,我使用$clinics->forget($key);。
假设现在集合中可能有100项。
目前为止还不错(如果不是分页的话)。
但是现在,当我使用分页的时候,大部分页面都是空白的,分页显示有200页,尽管只有100项,每页30页就有4页了。
我相信这是因为集合中的键被遗忘了,但是分页仍然假定整个集合。
如何用laravel重新索引集合,并且仍然有分页功能?
我可以做一个scopeGetDistance,但是在查询中,我如何根据计算来做一个“获取这个项目,并把这个项目排除在外”呢?
我对此进行了调查:
更新:
以下代码属于作用域:
public function scopeCloseTo($query, $lat, $long)
{
return $query->whereRaw("
ST_Distance_Sphere(
point(long, lat),
point(?, ?)
) * .000621371192 < 20
", [
$long,
$lat,
]);
}这将返回错误:
SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax;
check the manual that corresponds to your MySQL server version for the right syntax
to use near 'long, lat), point(?, ?) ) * .000621371192 < 20 ' at line 3 (SQL: select count(*)
as aggregate from `clinics` where ST_Distance_Sphere( point(long, lat), point(11.816458, 55.451428) )
* .000621371192 < 20 and `clinic_type_id` = 1)发布于 2022-05-20 06:24:14
当您根据纬度和经度计算距离时,可以使用ST_Distance_Sphere函数在mysql中直接得到它。您可以在这个博客(球体实例)中了解更多有关此功能的信息。
在查询中,您将获取所有诊所,然后检查距离是否超过20公里,如果不是,则从分页对象中删除它,因此它创建了一个问题。因此,在mysql查询中直接进行验证,这样分页对象将始终提供所需的数据。以下是一个雄辩的查询,这将只返回诊所,其中超过20公里的用户。
Clinic::orderBy('name', 'asc')
->whereRaw(ST_Distance_Sphere(point('clinic_longitude', clinic_latitude), point($user_longitude, $user_latitude)) > 20000
->paginate(30)
->withQueryString();https://stackoverflow.com/questions/72305129
复制相似问题