如何对 Laravel 5 中的合并集合进行分页?
How can I paginate a merged collection in Laravel 5?
我正在创建一个流,其中包含两种类型的对象,BluePerson 和 RedPerson。为了创建流,我获取了所有这两个对象,然后将它们合并到一个集合中。这样做之后,我需要对它们进行分页,但是分页似乎是针对 eloquent 模型和数据库查询,而不是集合。我已经看到很多关于手动创建分页器的信息,但是文档,尤其是 API 中的文档很少(我什至无法找到分页器 class 接受的参数。)
如何对合并集合的结果进行分页?
public function index()
{
$bluePerson = BluePerson::all();
$redPerson = RedPerson::all();
$people = $bluePerson->merge($redPerson)->sortByDesc('created_at');
return view('stream.index')->with('people', $people);
}
尝试关注。
$arr = $pets->toArray();
$paginator->make($arr, count($arr), $perPage);
however paginate is for eloquent models and DB queries, and not collections, it seems.
你是对的。但是集合需要一个分页器功能。 forPage
语法:
Collection forPage(int $page, int $perPage)
示例:
休息很简单。
public function foo()
{
$collection = collect([1,2,3,4,5,6,7,8,9,0]);
$items = $collection->forPage($_GET['page'], 5); //Filter the page var
dd($items);
}
您可以尝试对两个集合进行分页并合并它们。您可以在 docs and the api 中找到有关分页的更多信息。这是手动创建您自己的分页器的示例...
$perPage = 20;
$blue = BluePerson::paginate($perPage / 2);
$red = RedPerson::paginate($perPage - count($blue));
$people = PaginationMerger::merge($blue, $red);
我在下面包含了 PaginationMerger class。
use Illuminate\Pagination\LengthAwarePaginator;
class PaginationMerger
{
/**
* Merges two pagination instances
*
* @param Illuminate\Pagination\LengthAwarePaginator $collection1
* @param Illuminate\Pagination\LengthAwarePaginator $collection2
* @return Illuminate\Pagination\LengthAwarePaginator
*/
static public function merge(LengthAwarePaginator $collection1, LengthAwarePaginator $collection2)
{
$total = $collection1->total() + $collection2->total();
$perPage = $collection1->perPage() + $collection2->perPage();
$items = array_merge($collection1->items(), $collection2->items());
$paginator = new LengthAwarePaginator($items, $total, $perPage);
return $paginator;
}
}
如果您想使用 LengthAwarePaginator,只需实例化一个。正如先前答案的评论中所述,您必须为此设置路径。您还需要确保在实例化分页器之前解析 "currentPage" 并设置要返回的项目。这都可以通过before/on实例化来完成。所以一个函数可能看起来像:
function paginateCollection($collection, $perPage, $pageName = 'page', $fragment = null)
{
$currentPage = \Illuminate\Pagination\LengthAwarePaginator::resolveCurrentPage($pageName);
$currentPageItems = $collection->slice(($currentPage - 1) * $perPage, $perPage);
parse_str(request()->getQueryString(), $query);
unset($query[$pageName]);
$paginator = new \Illuminate\Pagination\LengthAwarePaginator(
$currentPageItems,
$collection->count(),
$perPage,
$currentPage,
[
'pageName' => $pageName,
'path' => \Illuminate\Pagination\LengthAwarePaginator::resolveCurrentPath(),
'query' => $query,
'fragment' => $fragment
]
);
return $paginator;
}
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Collection;
use Illuminate\Pagination\Paginator;
您可以在 Providers/AppServiceProvider 中的 public 函数 boot() 中为 Collection 添加以下代码。
// Enable pagination
if (!Collection::hasMacro('paginate')) {
Collection::macro('paginate',
function ($perPage = 15, $page = null, $options = []) {
$page = $page ?: (Paginator::resolveCurrentPage() ?: 1);
return (new LengthAwarePaginator(
$this->forPage($page, $perPage)->values()->all(), $this->count(), $perPage, $page, $options))
->withPath('');
});
}
然后,您可以从集合中调用分页,就像 Eloquent 模型一样。例如
$pages = collect([1, 2, 3, 4, 5, 6, 7, 8, 9])->paginate(5);
分页的最佳方式collection:
1- 将此添加到 \app\Providers\AppServiceProvider
中的引导功能
/*
* use Illuminate\Support\Collection;
* use Illuminate\Pagination\LengthAwarePaginator;
*
* Paginate a standard Laravel Collection.
*
* @param int $perPage
* @param int $total
* @param int $page
* @param string $pageName
* @return array
*/
Collection::macro('paginate', function($perPage, $total = null, $page = null, $pageName = 'page') {
$page = $page ?: LengthAwarePaginator::resolveCurrentPage($pageName);
return new LengthAwarePaginator(
$this->forPage($page, $perPage),
$total ?: $this->count(),
$perPage,
$page,
[
'path' => LengthAwarePaginator::resolveCurrentPath(),
'pageName' => $pageName,
]
);
});
2-以后所有 collection 你都可以像你的代码一样分页
$people->paginate(5)
我在一个项目中不得不处理类似的事情,在其中一个页面中我必须显示两种类型的出版物分页 和 按 created_at 字段排序。我的例子是Post模型和Event模型(以下简称出版物).
唯一的区别是我不想从数据库中获取所有出版物然后合并并对结果进行排序,正如您可以想象的那样,如果我们有数百个出版物,这将引发性能问题。
所以我发现对每个模型进行分页然后合并和排序会更方便。
这就是我所做的(基于之前发布的答案和评论)
首先让我给你看一个简化版本的"my solution",然后我会尽可能多地解释代码。
use App\Models\Post;
use App\Models\Event;
use App\Facades\Paginator;
class PublicationsController extends Controller
{
/**
* Display a listing of the resource.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function index(Request $request)
{
$events = Event::latest()->paginate(5);
$posts = Post::latest()->paginate(5);
$publications = Paginator::merge($events, $posts)->sortByDesc('created_at')->get();
return view('publications.index', compact('publications'));
}
}
你现在已经猜到了,外观分页器负责合并和排序我的分页器($events
& $posts
)
为了使这个答案更加清晰和完整,我将向您展示如何创建您自己的 Facade。
您可以选择将自己的外观放在任何您喜欢的地方,就我个人而言,我选择将它们放在应用程序文件夹下的 Facades 文件夹中,就像这棵树中所示。
+---app
| +---Console
| +---Events
| +---Exceptions
| +---Exports
| +---Facades
| | +---Paginator.php
| | +---...
| +---Http
| | +---Controllers
. . +---...
. . .
将这段代码放入app/Facades/Paginator.php
namespace App\Facades;
use Illuminate\Support\Facades\Facade;
class Paginator extends Facade
{
/**
* Get the registered name of the component.
*
* @return string
*/
protected static function getFacadeAccessor()
{
return 'paginator';
}
}
更多信息,您可以查看How Facades Work
下一步,绑定分页器到服务容器,打开app\Providers\AppServiceProvider.php
namespace App\Providers;
use App\Services\Pagination\Paginator;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
$this->app->bind('paginator', function ($app) {
return new Paginator;
});
}
}
更多信息,您可以查看The Boot Method
我的分页器 class 在 app/Services/Pagination/
文件夹下。同样,您可以将 classes 放在任何您喜欢的地方。
namespace App\Services\Pagination;
use Illuminate\Support\Arr;
use InvalidArgumentException;
use Illuminate\Support\Collection;
use Illuminate\Pagination\LengthAwarePaginator;
class Paginator
{
/**
* All of the items being paginated.
*
* @var \Illuminate\Support\Collection
*/
protected $items;
/**
* The number of items to be shown per page.
*
* @var int
*/
protected $perPage;
/**
* The total number of items before slicing.
*
* @var int
*/
protected $total;
/**
* The base path to assign to all URLs.
*
* @var string
*/
protected $path = '/';
/**
* Merge paginator instances
*
* @param mixed $paginators
* @param bool $descending
* @return \Illuminate\Pagination\LengthAwarePaginator
*/
function merge($paginators)
{
$paginators = is_array($paginators) ? $paginators : func_get_args();
foreach ($paginators as $paginator) {
if (!$paginator instanceof LengthAwarePaginator) {
throw new InvalidArgumentException("Only LengthAwarePaginator may be merged.");
}
}
$total = array_reduce($paginators, function($carry, $paginator) {
return $paginator->total();
}, 0);
$perPage = array_reduce($paginators, function($carry, $paginator) {
return $paginator->perPage();
}, 0);
$items = array_map(function($paginator) {
return $paginator->items();
}, $paginators);
$items = Arr::flatten($items);
$items = Collection::make($items);
$this->items = $items;
$this->perPage = $perPage;
$this->total = $total;
return $this;
}
/**
* Sort the collection using the given callback.
*
* @param callable|string $callback
* @param int $options
* @param bool $descending
* @return static
*/
public function sortBy($callback, $options = SORT_REGULAR, $descending = false)
{
$this->items = $this->items->sortBy($callback, $options, $descending);
return $this;
}
/**
* Sort the collection in descending order using the given callback.
*
* @param callable|string $callback
* @param int $options
* @return static
*/
public function sortByDesc($callback, $options = SORT_REGULAR)
{
return $this->sortBy($callback, $options, true);
}
/**
* Get paginator
*
* @return \Illuminate\Pagination\LengthAwarePaginator
*/
public function get()
{
return new LengthAwarePaginator(
$this->items,
$this->total,
$this->perPage,
LengthAwarePaginator::resolveCurrentPage(),
[
'path' => LengthAwarePaginator::resolveCurrentPath(),
]
);
}
}
肯定有改进的余地,所以如果您看到需要更改的内容,请在此处发表评论或通过 twitter 与我联系。
您可以像下面这样更改:
public function index()
{
$bluePerson = BluePerson::paginate();
$redPerson = RedPerson::all();
$people = $bluePerson->merge($redPerson)->sortByDesc('created_at');
return view('stream.index')->with('people', $people);
}
似乎分页不再是laravel 8
中集合的一部分,所以我使用了laravel的Illuminate\Pagination\Paginator
class来对数据进行分页,但是有一个问题,分页相关信息正在通过分页更新,但数据根本没有分页!
我找到问题了,laravel的Paginator
class没有正确分页数据,你可以看class的原方法。
/**
* Set the items for the paginator.
*
* @param mixed $items
* @return void
*/
protected function setItems($items)
{
$this->items = $items instanceof Collection ? $items : Collection::make($items);
$this->hasMore = $this->items->count() > $this->perPage;
$this->items = $this->items->slice(0, $this->perPage);
}
所以,我构建了自己的 Paginator
class 并从 laravel 的 Paginator
class 扩展了它,并解决了我的问题已经在下面向您展示了。
use Illuminate\Support\Collection;
class Paginator extends \Illuminate\Pagination\Paginator
{
/**
* Set the items for the paginator.
*
* @param mixed $items
* @return void
*/
protected function setItems($items)
{
$this->items = $items instanceof Collection ? $items : Collection::make($items);
$this->hasMore = $this->items->count() > ($this->perPage * $this->currentPage);
$this->items = $this->items->slice(
($this->currentPage - 1) * $this->perPage,
$this->perPage
);
}
}
class的用法如下
(new Paginator(
$items,
$perPage = 10,
$page = 1, [
'path' => $request->url(),
]
))->toArray(),
注:如果要使用laravel的Paginator
作为views
,可以使用render()
方法而不是 toArray()
方法。
我的数据分页现在工作正常。
希望对你有用。
use Illuminate\Support\Collection;
$collection = new Collection;
$collectionA = ModelA::all();
$collectionB = ModelB::all();
$merged_collection = $collectionA->merge($collectionB);
foreach ($merged_collection as $item) {
$collection->push($item);
}
$paginated_collection = $collection->paginate(10);
我正在创建一个流,其中包含两种类型的对象,BluePerson 和 RedPerson。为了创建流,我获取了所有这两个对象,然后将它们合并到一个集合中。这样做之后,我需要对它们进行分页,但是分页似乎是针对 eloquent 模型和数据库查询,而不是集合。我已经看到很多关于手动创建分页器的信息,但是文档,尤其是 API 中的文档很少(我什至无法找到分页器 class 接受的参数。)
如何对合并集合的结果进行分页?
public function index()
{
$bluePerson = BluePerson::all();
$redPerson = RedPerson::all();
$people = $bluePerson->merge($redPerson)->sortByDesc('created_at');
return view('stream.index')->with('people', $people);
}
尝试关注。
$arr = $pets->toArray();
$paginator->make($arr, count($arr), $perPage);
however paginate is for eloquent models and DB queries, and not collections, it seems.
你是对的。但是集合需要一个分页器功能。 forPage
语法:
Collection forPage(int $page, int $perPage)
示例:
休息很简单。
public function foo()
{
$collection = collect([1,2,3,4,5,6,7,8,9,0]);
$items = $collection->forPage($_GET['page'], 5); //Filter the page var
dd($items);
}
您可以尝试对两个集合进行分页并合并它们。您可以在 docs and the api 中找到有关分页的更多信息。这是手动创建您自己的分页器的示例...
$perPage = 20;
$blue = BluePerson::paginate($perPage / 2);
$red = RedPerson::paginate($perPage - count($blue));
$people = PaginationMerger::merge($blue, $red);
我在下面包含了 PaginationMerger class。
use Illuminate\Pagination\LengthAwarePaginator;
class PaginationMerger
{
/**
* Merges two pagination instances
*
* @param Illuminate\Pagination\LengthAwarePaginator $collection1
* @param Illuminate\Pagination\LengthAwarePaginator $collection2
* @return Illuminate\Pagination\LengthAwarePaginator
*/
static public function merge(LengthAwarePaginator $collection1, LengthAwarePaginator $collection2)
{
$total = $collection1->total() + $collection2->total();
$perPage = $collection1->perPage() + $collection2->perPage();
$items = array_merge($collection1->items(), $collection2->items());
$paginator = new LengthAwarePaginator($items, $total, $perPage);
return $paginator;
}
}
如果您想使用 LengthAwarePaginator,只需实例化一个。正如先前答案的评论中所述,您必须为此设置路径。您还需要确保在实例化分页器之前解析 "currentPage" 并设置要返回的项目。这都可以通过before/on实例化来完成。所以一个函数可能看起来像:
function paginateCollection($collection, $perPage, $pageName = 'page', $fragment = null)
{
$currentPage = \Illuminate\Pagination\LengthAwarePaginator::resolveCurrentPage($pageName);
$currentPageItems = $collection->slice(($currentPage - 1) * $perPage, $perPage);
parse_str(request()->getQueryString(), $query);
unset($query[$pageName]);
$paginator = new \Illuminate\Pagination\LengthAwarePaginator(
$currentPageItems,
$collection->count(),
$perPage,
$currentPage,
[
'pageName' => $pageName,
'path' => \Illuminate\Pagination\LengthAwarePaginator::resolveCurrentPath(),
'query' => $query,
'fragment' => $fragment
]
);
return $paginator;
}
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Collection;
use Illuminate\Pagination\Paginator;
您可以在 Providers/AppServiceProvider 中的 public 函数 boot() 中为 Collection 添加以下代码。
// Enable pagination
if (!Collection::hasMacro('paginate')) {
Collection::macro('paginate',
function ($perPage = 15, $page = null, $options = []) {
$page = $page ?: (Paginator::resolveCurrentPage() ?: 1);
return (new LengthAwarePaginator(
$this->forPage($page, $perPage)->values()->all(), $this->count(), $perPage, $page, $options))
->withPath('');
});
}
然后,您可以从集合中调用分页,就像 Eloquent 模型一样。例如
$pages = collect([1, 2, 3, 4, 5, 6, 7, 8, 9])->paginate(5);
分页的最佳方式collection:
1- 将此添加到 \app\Providers\AppServiceProvider
中的引导功能 /*
* use Illuminate\Support\Collection;
* use Illuminate\Pagination\LengthAwarePaginator;
*
* Paginate a standard Laravel Collection.
*
* @param int $perPage
* @param int $total
* @param int $page
* @param string $pageName
* @return array
*/
Collection::macro('paginate', function($perPage, $total = null, $page = null, $pageName = 'page') {
$page = $page ?: LengthAwarePaginator::resolveCurrentPage($pageName);
return new LengthAwarePaginator(
$this->forPage($page, $perPage),
$total ?: $this->count(),
$perPage,
$page,
[
'path' => LengthAwarePaginator::resolveCurrentPath(),
'pageName' => $pageName,
]
);
});
2-以后所有 collection 你都可以像你的代码一样分页
$people->paginate(5)
我在一个项目中不得不处理类似的事情,在其中一个页面中我必须显示两种类型的出版物分页 和 按 created_at 字段排序。我的例子是Post模型和Event模型(以下简称出版物).
唯一的区别是我不想从数据库中获取所有出版物然后合并并对结果进行排序,正如您可以想象的那样,如果我们有数百个出版物,这将引发性能问题。
所以我发现对每个模型进行分页然后合并和排序会更方便。
这就是我所做的(基于之前发布的答案和评论)
首先让我给你看一个简化版本的"my solution",然后我会尽可能多地解释代码。
use App\Models\Post;
use App\Models\Event;
use App\Facades\Paginator;
class PublicationsController extends Controller
{
/**
* Display a listing of the resource.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function index(Request $request)
{
$events = Event::latest()->paginate(5);
$posts = Post::latest()->paginate(5);
$publications = Paginator::merge($events, $posts)->sortByDesc('created_at')->get();
return view('publications.index', compact('publications'));
}
}
你现在已经猜到了,外观分页器负责合并和排序我的分页器($events
& $posts
)
为了使这个答案更加清晰和完整,我将向您展示如何创建您自己的 Facade。
您可以选择将自己的外观放在任何您喜欢的地方,就我个人而言,我选择将它们放在应用程序文件夹下的 Facades 文件夹中,就像这棵树中所示。
+---app
| +---Console
| +---Events
| +---Exceptions
| +---Exports
| +---Facades
| | +---Paginator.php
| | +---...
| +---Http
| | +---Controllers
. . +---...
. . .
将这段代码放入app/Facades/Paginator.php
namespace App\Facades;
use Illuminate\Support\Facades\Facade;
class Paginator extends Facade
{
/**
* Get the registered name of the component.
*
* @return string
*/
protected static function getFacadeAccessor()
{
return 'paginator';
}
}
更多信息,您可以查看How Facades Work
下一步,绑定分页器到服务容器,打开app\Providers\AppServiceProvider.php
namespace App\Providers;
use App\Services\Pagination\Paginator;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
$this->app->bind('paginator', function ($app) {
return new Paginator;
});
}
}
更多信息,您可以查看The Boot Method
我的分页器 class 在 app/Services/Pagination/
文件夹下。同样,您可以将 classes 放在任何您喜欢的地方。
namespace App\Services\Pagination;
use Illuminate\Support\Arr;
use InvalidArgumentException;
use Illuminate\Support\Collection;
use Illuminate\Pagination\LengthAwarePaginator;
class Paginator
{
/**
* All of the items being paginated.
*
* @var \Illuminate\Support\Collection
*/
protected $items;
/**
* The number of items to be shown per page.
*
* @var int
*/
protected $perPage;
/**
* The total number of items before slicing.
*
* @var int
*/
protected $total;
/**
* The base path to assign to all URLs.
*
* @var string
*/
protected $path = '/';
/**
* Merge paginator instances
*
* @param mixed $paginators
* @param bool $descending
* @return \Illuminate\Pagination\LengthAwarePaginator
*/
function merge($paginators)
{
$paginators = is_array($paginators) ? $paginators : func_get_args();
foreach ($paginators as $paginator) {
if (!$paginator instanceof LengthAwarePaginator) {
throw new InvalidArgumentException("Only LengthAwarePaginator may be merged.");
}
}
$total = array_reduce($paginators, function($carry, $paginator) {
return $paginator->total();
}, 0);
$perPage = array_reduce($paginators, function($carry, $paginator) {
return $paginator->perPage();
}, 0);
$items = array_map(function($paginator) {
return $paginator->items();
}, $paginators);
$items = Arr::flatten($items);
$items = Collection::make($items);
$this->items = $items;
$this->perPage = $perPage;
$this->total = $total;
return $this;
}
/**
* Sort the collection using the given callback.
*
* @param callable|string $callback
* @param int $options
* @param bool $descending
* @return static
*/
public function sortBy($callback, $options = SORT_REGULAR, $descending = false)
{
$this->items = $this->items->sortBy($callback, $options, $descending);
return $this;
}
/**
* Sort the collection in descending order using the given callback.
*
* @param callable|string $callback
* @param int $options
* @return static
*/
public function sortByDesc($callback, $options = SORT_REGULAR)
{
return $this->sortBy($callback, $options, true);
}
/**
* Get paginator
*
* @return \Illuminate\Pagination\LengthAwarePaginator
*/
public function get()
{
return new LengthAwarePaginator(
$this->items,
$this->total,
$this->perPage,
LengthAwarePaginator::resolveCurrentPage(),
[
'path' => LengthAwarePaginator::resolveCurrentPath(),
]
);
}
}
肯定有改进的余地,所以如果您看到需要更改的内容,请在此处发表评论或通过 twitter 与我联系。
您可以像下面这样更改:
public function index()
{
$bluePerson = BluePerson::paginate();
$redPerson = RedPerson::all();
$people = $bluePerson->merge($redPerson)->sortByDesc('created_at');
return view('stream.index')->with('people', $people);
}
似乎分页不再是laravel 8
中集合的一部分,所以我使用了laravel的Illuminate\Pagination\Paginator
class来对数据进行分页,但是有一个问题,分页相关信息正在通过分页更新,但数据根本没有分页!
我找到问题了,laravel的Paginator
class没有正确分页数据,你可以看class的原方法。
/**
* Set the items for the paginator.
*
* @param mixed $items
* @return void
*/
protected function setItems($items)
{
$this->items = $items instanceof Collection ? $items : Collection::make($items);
$this->hasMore = $this->items->count() > $this->perPage;
$this->items = $this->items->slice(0, $this->perPage);
}
所以,我构建了自己的 Paginator
class 并从 laravel 的 Paginator
class 扩展了它,并解决了我的问题已经在下面向您展示了。
use Illuminate\Support\Collection;
class Paginator extends \Illuminate\Pagination\Paginator
{
/**
* Set the items for the paginator.
*
* @param mixed $items
* @return void
*/
protected function setItems($items)
{
$this->items = $items instanceof Collection ? $items : Collection::make($items);
$this->hasMore = $this->items->count() > ($this->perPage * $this->currentPage);
$this->items = $this->items->slice(
($this->currentPage - 1) * $this->perPage,
$this->perPage
);
}
}
class的用法如下
(new Paginator(
$items,
$perPage = 10,
$page = 1, [
'path' => $request->url(),
]
))->toArray(),
注:如果要使用laravel的Paginator
作为views
,可以使用render()
方法而不是 toArray()
方法。
我的数据分页现在工作正常。
希望对你有用。
use Illuminate\Support\Collection;
$collection = new Collection;
$collectionA = ModelA::all();
$collectionB = ModelB::all();
$merged_collection = $collectionA->merge($collectionB);
foreach ($merged_collection as $item) {
$collection->push($item);
}
$paginated_collection = $collection->paginate(10);