原始查询的手动分页laravel



Am正在尝试为laravel中的原始查询创建手动分页。在检查laravel文档时,我发现使用Paginator这样的方法:`

$appliers=分页器::make($appliers,$totalAppliers,4);`

但是,当我返回$appliers时,它会给我所有的记录,而不是我的Paginator::make方法中要求的4条记录,但如果我在我的应用程序上调用links()方法,比如:$appliers->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);

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

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

因为用$applicants调用Paginator::make,所以您已经获得了所有记录,您可以尝试以下操作:

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

分页器计算分页链接,因此不会影响查询。

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

最新更新