简体   繁体   English

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

[英]How to use raw sql Pagination in Laravel5?

This is my Controller code:这是我的控制器代码:

$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 ) );

How can I add pagination to this code to build my restful api?如何向此代码添加分页以构建我的 Restful api?

iOS or android will send the "next page" parameter, how to use it and find the next section data? iOS或者android都会发送“next page”参数,如何使用和查找下一段数据?

As far as I know you can't paginate raw query, here's why:据我所知,您无法对原始查询进行分页,原因如下:

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

$result here will have the array type and paginate() is the method from the Illuminate\\Database\\Query\\Builder class.此处的$result将具有数组类型,而paginate()是来自Illuminate\\Database\\Query\\Builder类的方法。

Your case can be performed this way:您的案例可以这样执行:

$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;
}

As you can see minimal effort is needed here to separate raw query to selectRaw() and whereRaw() methods.正如您所看到的,将原始查询与selectRaw()whereRaw()方法分开只需要很少的努力。

Another option if you are trying to paginate dynamic columns that maybe you were processing calculations on for reporting is to create a sort method and pass in your array and params:如果您尝试对可能正在处理计算以进行报告的动态列进行分页,另一种选择是创建一个排序方法并传入您的数组和参数:

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);

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM