Laravel 的分页究竟是如何工作的?

2022-01-04 00:00:00 php laravel pagination

我需要澄清一下 Laravel 的分页器在后台是如何工作的:假设我有一个 1000 行的表,我使用$results = Model::paginate(100);如果我理解正确,Eloquent 将带回一个包含表中所有行 (1000) 的集合,将其切成较小的 100 行集合,并将分页按钮数据附加到它们.现在 $results 包含 Page 1 集合和按钮的分页数据.我的问题是:当我按下 Page 2 按钮时,后台会发生什么?Eloquent 会再次查询数据库,再次检索整个 1000 行集合,将其切片并返回 Page 2 集合,还是在我之前的请求已检索回的集合上工作?或者,Eloquent 的 ::paginate(100) 是否使用限制查询数据库?喜欢select * from table limit 100?

I need some clarifications about how Laravel's paginator works in the background: Say I have a table with 1000 rows and I use $results = Model::paginate(100); If I understood correctly, Eloquent will bring back a collection containing all the rows (1000) from the table, slice it in smaller, 100 rows collections and attach the pagination buttons data to them. Now $results contains the Page 1 collection and the pagination data for the buttons. My question is: what happens in the background when I press Page 2 button? Will Eloquent query the database again, retrieve the whole 1000 rows collection again, slice it and return the Page 2 collection, or does it work on the collection already retrieved back by my previous request? Or, does Eloquent's ::paginate(100) query the database using limits? Like select * from table limit 100?

推荐答案

您可以使用 Laravel Telescope 来查看 Laravel 的工作原理.在查询选项卡上,您将看到发出请求时执行的查询(如果未启用缓存).

You can use Laravel Telescope to see how Laravel works. On the queries tab you will see what queries executed when you make requests (if caching is not enabled).

相关文章