简体   繁体   English

覆盖Laravel中的分页器项目

[英]Overwrite paginator items in Laravel

I have a list of ids that come from a complicated query. 我有一个来自复杂查询的ID列表。 I paginate the response of that complicated query and then use those ids to get the eloquent models. 我对那个复杂查询的响应进行了分页,然后使用这些ID来获得雄辩的模型。 I then put it through a resource with the pagination meta data. 然后,我将其与分页元数据一起放入资源中。

The laravel AbstractPaginator class protects the items attribute so you cannot easily overwrite them. laravel AbstractPaginator类保护items属性,因此您不能轻易覆盖它们。 I have a solution to use a ReflectionProperty but I'm after a simpler solution. 我有一个使用ReflectionProperty的解决方案,但是我正在寻求一个更简单的解决方案。

The below works but it is not particularly elegant. 下面的作品,但不是特别优雅。

// $studentIds == Long complicated query that would return 1000s of students
$data = $studentIds->paginate(); // Execute the query limited to 15.

// Use ids to get eloquent models for our students
$students = Student::whereIn('id', $data->pluck('id'))->get();

// Overwrite paginate `items` attribute so that our response contains pagination meta.
$rp = new \ReflectionProperty('Illuminate\Pagination\AbstractPaginator', 'items');
$rp->setAccessible(true);
$rp->setValue($data, $students);

return new StudentResourceCollection($data);

使用setCollection()方法:

$data->setCollection($students);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM