如何在 Laravel5 中使用原始 sql 分页?

How to use raw sql Pagination in Laravel5?

这是我的控制器代码:

$sql = "SELECT *,earth_distance(ll_to_earth(team.lat, team.lng), ll_to_earth(23.1215939329,113.3096030895)) AS distance FROM team where earth_box(ll_to_earth(23.1215939329,113.3096030895),1000) @> ll_to_earth(team.lat, team.lng); ";
$result = DB::select( \DB::raw( $sql ) );

如何向此代码添加分页以构建我的 restful api?

iOS或android会发送"next page"参数,如何使用它并找到下一段数据?

据我所知,您不能对原始查询进行分页,原因如下:

$result = DB::select($sql); 

$result 这里将有数组类型,paginate()Illuminate\Database\Query\Builder class.

中的方法

您的案例可以这样处理:

$items = DB::table('team')   
    ->selectRaw('SELECT *,earth_distance(ll_to_earth(team.lat, team.lng), ll_to_earth(23.1215939329,113.3096030895)) AS distance')
    ->whereRaw('earth_box(ll_to_earth(23.1215939329,113.3096030895),1000) @> ll_to_earth(team.lat, team.lng)')
    ->paginate(10);

foreach($items as $item) {
    echo $item->distance;
}

如您所见,将原始查询分离为 selectRaw()whereRaw() 方法所需的工作很少。

如果您尝试对动态列进行分页,您可能正在处理用于报告的计算,那么另一种选择是创建一个排序方法并传入您的数组和参数:

public function sort($array_of_objects, $sort_by=null, $order, $page) 
{
    $collection = collect($array_of_objects);
    if ($sort_by)
    {

        if ($order=='desc') {
            $sorted = $collection->sortBy(function($role) use ($sort_by)
            {
                return $role->{$sort_by};
            })->reverse();
        } else if ($order=='asc') {
            $sorted = $collection->sortBy(function($role) use ($sort_by)
            {
                return $role->{$sort_by};
            });
        }
    } else {
        $sorted = $collection;
    }

    $num_per_page = 20;
    if (!$page) {
        $page = 1;
    }

    $offset = ( $page - 1) * $num_per_page;
    $sorted = $sorted->splice($offset, $num_per_page);

    return  new Paginator($sorted, count($array_of_objects), $num_per_page, $page);

}