How to use raw sql Pagination in Laravel5?

后端 未结 2 1967
逝去的感伤
逝去的感伤 2020-12-20 06:17

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 tea         


        
相关标签:
2条回答
  • 2020-12-20 06:32

    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.

    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.

    0 讨论(0)
  • 2020-12-20 06:54

    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);
    
    }
    
    0 讨论(0)
提交回复
热议问题