[英]Overwrite paginator items in Laravel
我有一個來自復雜查詢的ID列表。 我對那個復雜查詢的響應進行了分頁,然后使用這些ID來獲得雄辯的模型。 然后,我將其與分頁元數據一起放入資源中。
laravel AbstractPaginator
類保護items
屬性,因此您不能輕易覆蓋它們。 我有一個使用ReflectionProperty
的解決方案,但是我正在尋求一個更簡單的解決方案。
下面的作品,但不是特別優雅。
// $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.