Laravel 5.2 - 过滤自定义属性然后分页

时间:2016-06-03 19:11:20

标签: php laravel

所以我知道如何使用paginate()进行分页,并且我知道如何基于Accessor(集合上的where())进行过滤。但是,paginate接受查询构建器并且集合上的where()返回集合。

所以如果我想通过自定义属性获取一堆项目/过滤器然后对结果集进行分页....我该怎么做?

访问器:

public function getRequiredToReportAttribute()
{
  // return boolean based off of complicated business logic
}

索引方法:

public function index()
{
    //what im doing (redacted)
    $employers = (new App\Employers')->paginate($this->perPage);

    // what I would like to be doing
    $employers = (new App\Employers)->where('required_to_report', '=', true)->paginate($this->perPage);


    return $this->sendResponse($employers);
}

2 个答案:

答案 0 :(得分:3)

如果您想使用加速器,可以在收到查询后迭代收集,如下所示:

 $result = Model::get()->filter(function($item) {
    return $item->require_to_report === true;
 });

在这里,您拥有模型的所有记录,然后您可以创建手动分页器:

 $paginator = new Illuminate\Pagination\Paginator($result, 10);

当你有太多记录时,你有这种方法的弱点,性能可能会受到影响。

答案 1 :(得分:0)

基于Jose Rojas answerthis post,我构建了一个LengthAwarePaginator,用于对属性访问器进行集合筛选。这是一个操作方法示例:

$collection = Model::all();

//Filter your collection
$filteredItems = $collection->filter(function($col) {
    return $col->require_to_report === true;
});

// Setup necessary information for LengthAwarePaginator
$currentPage = LengthAwarePaginator::resolveCurrentPage();
$pageLimit = 20;

// slice the current page items       
$currentItems = $filteredItems->slice(pageLimit * ($currentPage - 1), pageLimit);

// you may not need the $path here but might be helpful..
$path = "/api/v1/employers";

// Build the new paginator
$paginator = new LengthAwarePaginator($currentItems, count($filteredItems), $pageLimit, $currentPage, ['path' => $path]);

return $paginator;