php - 自动构建 laravel 分页对象
问题描述
在我的应用程序中,每次我从数据库中检索分页结果时,我都必须这样做:
$posts = Post::latest()->with(['category','user'])->paginate($request->input('paginate', 6));
$posts =
[
'data' => $posts,
'pagination' => [
'total' => $posts->total(),
'per_page' =>$posts->perPage(),
'current_page' => $posts->currentPage(),
'last_page' => $posts->lastPage(),
'from' => $posts->firstItem(),
'to' => $posts->lastItem()
]
];
如您所见,我首先从数据库中检索结果,然后我必须手动创建分页数据数组,老实说,总是做同样的事情对我来说似乎很糟糕和乏味,我想知道是否有 laravel 魔术方法来自动构建分页有效负载大批?
解决方案
您可以使用 Eloquent:API 资源“ https://laravel.com/docs/7.x/eloquent-resources ”
您应该创建一个资源:php artisan make:resource PostCollection
你应该改变toArray($request)
这样的方法:
public function toArray($request)
{
return [
'data' => $this->collection,
'pagination' => [
'total' => $this->total(),
'per_page' =>$this->perPage(),
'current_page' => $this->currentPage(),
'last_page' => $this->lastPage(),
'from' => $this->firstItem(),
'to' => $this->lastItem()
]
];
}
现在,当您想对模型进行分页时,您只需这样做:
//Get posts
$posts = Post::latest()->with(['category','user'])
->paginate($request->input('paginate', 6)));
//Use your resource (Collection)
$postsPaginate = new PostCollection($posts);
//Return your resource
return $porstsPaginate;
推荐阅读
- java - Android RecyclerView“找不到符号变量”
- php - PHP:子类无法访问 MySQL 对象
- linux - 从 .so 文件中删除路径以便 RPM check-buildroot 成功
- r - 如果每季度某一天数的行 = 0,则删除所有行
- mysql - 如何在mysql服务器中为用户设置远程访问?
- android - PagedList 和 RecyclerView 交互的性能可以提高吗?
- sql-server - 查询临时表中的重复行导致不重复的行
- mysql - 如何在没有重复组的实体框架核心中分组?
- php - 在 php 购物车中找不到数组项
- javascript - 将 vanilla js 库添加到 Nuxt