手动分页原始查询laravel

时间:2014-11-08 12:27:26

标签: laravel pagination

我试图在laravel中创建原始查询的手动分页。检查laravel文档,我看到使用Paginator方法:`

$ applicants = Paginator :: make($ applicants,$ totalApplicants,4);`

但是当我返回$申请人时,它会给我所有记录,而不是我在Paginator :: make方法中请求的4,但如果我在我的申请人上调用链接()mehod,例如:$ applicants-> links()它返回到我视图的分页链接

请问我做错了什么,或者我需要写一个方法来完成这项工作

来自我的控制器的代码:

$statement3 = "SELECT * FROM applicant where lga = '$appulga' ";

        //loop through lga id to build query
        foreach($LGA_Names as $lga)
        {
            $statement3.= " "."OR"." "."lga=". "'".$lga."'";
        }

        //FAcility for User assigned LGA
        $applicants = DB::Select($statement3);
        ///////////////////////////////////////////////////////////////
        $totalApplicants = count($applicants);
        $perpage = 4;

        $applicants = Paginator::make($applicants,$totalApplicants,$perpage);

3 个答案:

答案 0 :(得分:1)

Paginator不会拆分集合,您必须手动处理结果。

$page = Paginator::getCurrentPage(); // Get the current page for the request

$limit = 4;
$offset = $page * $limit;

// query to get `COUNT(*)`
// query to get results with `LIMIT $offset, $limit`

Paginator::make($results, $total, $limit);

手动编写sql查询无效且不安全,请改用查询生成器;

$query = DB::table('applicant')->where('lga', $appulga);

foreach ($LGA_Names as $lga)
{
    $query->orWhere('lga', $lga);
}

$applicants = $query->paginate(4);

答案 1 :(得分:1)

您已获得所有记录,因为您使用Paginator::make致电$applicants,您可以尝试以下内容:

$pageNumber = Input::get('page', 1);
$perpage = 4;


$statement = "SELECT * FROM applicant where lga = '$appulga' ";
// ...
$applicants = DB::Select($statement);


$slice = array_slice($applicants, $perpage * ($pageNumber - 1), $perpage);
$applicants = Paginator::make($slice, count($applicants), $perpage);

答案 2 :(得分:1)

Paginator计算分页链接,因此它不会影响您的查询。

它只返回/Illuminate/Pagination/Paginator个对象,如果你想作为响应返回或传递给视图,它将返回在toArray方法中定义的数组元素。