php Laravel Eloquent 跳过 n,通吃?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27457249/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 23:22:54  来源:igfitidea点击:

Laravel Eloquent skip n, take all?

phplaraveleloquentoffset

提问by Helen Che

I've noticed that in Laravel when chaining a skip()you must also use take()as well. I want to skip the first n rows but take the rest. The take method only allows integers how can I do this without resorting to some hacky trick such as specifying a large number for take?

我注意到在 Laravel 中链接 a 时skip()也必须使用take()。我想跳过前 n 行但剩下的。take 方法只允许整数,我怎么能在不诉诸一些技巧的情况下做到这一点,例如为 take 指定一个大数字?

回答by Yousof K.

Basically, with every OFFSET, a LIMIT must be supplied for mysql to work. Therefore, there is no way to do this without sepcifying a limit. We need some php mojo to work here.

基本上,对于每个 OFFSET,必须为 mysql 提供一个 LIMIT 才能工作。因此,如果不指定限制,就无法做到这一点。我们需要一些 php mojo 才能在这里工作。

Let's say we have an Eloquent Class named Attendance. Here's what should work:

假设我们有一个名为Attendance. 这是应该起作用的:

//Getting count
$count = Attendance::count();
$skip = 5;
$limit = $count - $skip; // the limit
$collection = Attendance::skip($skip)->take($limit)->get();

回答by Franco Risso

I think this is not a good answer, because you're forcing to do two queries, the right way will be:

我认为这不是一个好的答案,因为您被迫进行两个查询,正确的方法是:

$collection = Attendance::skip($skip)->take($limit)->get();
$collection.shift();

You can see more about collections here

您可以在此处查看有关集合的更多信息

回答by SubRed

If you're using MySQL and you don't want to have 2 queries to get the max rows, you may use the PHP maximum INT value as take()parameter e.g. take(PHP_INT_MAX).

如果您正在使用 MySQL 并且您不想有 2 个查询来获取最大行数,您可以使用 PHP 最大 INT 值作为take()参数,例如take(PHP_INT_MAX).

It's because Laravel Query Grammar casts the limit to integer. So you can't use a larger number than that.

这是因为 Laravel Query Grammar将限制转换为 integer。所以你不能使用比这更大的数字。

From MySQL documentation on LIMIT:

来自LIMIT 上的 MySQL 文档

To retrieve all rows from a certain offset up to the end of the result set, you can use some large number for the second parameter.

要检索从某个偏移量到结果集末尾的所有行,您可以为第二个参数使用一些大数字。

For example:

例如:

\App\User::skip(10)->take(PHP_INT_MAX)->get();