How to use paginate() with a having() clause when column does not exist in table

前端 未结 7 1805
不知归路
不知归路 2020-12-01 06:41

I have a tricky case ...

Following database query does not work:

DB::table(\'posts\')
->select(\'posts.*\', DB::raw($haversineSQL . \' as distance         


        
相关标签:
7条回答
  • 2020-12-01 07:37

    You can use manual pagination as having behaving peculiar with pagination class.

    $posts = DB::table('posts')
        ->select('posts.*', DB::raw($haversineSQL . ' as distance'))
        ->having('distance', '<=', $distance)
        ->get();
    
    // Items per page
    $perPage = 10;
    $totalItems = count($posts);
    $totalPages = ceil($totalItems / $perPage);
    
    $page = Input::get('page', 1);
    
    if ($page > $totalPages or $page < 1) {
        $page = 1;
    }
    
    $offset = ($page * $perPage) - $perPage;
    
    $posts = array_slice($posts, $offset, $perPage);
    
    $posts = Paginator::make($posts, $totalItems, $perPage);
    
    
    dd($posts);
    
    0 讨论(0)
提交回复
热议问题