php 选择前 10 行 - Laravel Eloquent
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21255508/
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
Select the first 10 rows - Laravel Eloquent
提问by Jonnerz
So far I have the following model:
到目前为止,我有以下模型:
class Listing extends Eloquent {
//Class Logic HERE
}
I want a basic function that retrieves the first 10 rows of my table "listings" and passes them on to the view (via a controller?).
我想要一个基本函数来检索表“列表”的前 10 行并将它们传递给视图(通过控制器?)。
I know this a very basic task but I can't find a simple guide that actually explains step-by-step how to display a basic set of results, whilst detailing what is required in the model, controller and view files.
我知道这是一项非常基本的任务,但我找不到一个简单的指南来实际解释如何显示一组基本结果,同时详细说明模型、控制器和视图文件中的要求。
回答by Vit Kos
First you can use a Paginator. This is as simple as:
首先,您可以使用分页器。这很简单:
$allUsers = User::paginate(15);
$someUsers = User::where('votes', '>', 100)->paginate(15);
The variables will contain an instance of Paginator class. all of your data will be stored under datakey.
这些变量将包含一个分页器类的实例。您的所有数据都将存储在data密钥下。
Or you can do something like:
或者您可以执行以下操作:
Old versions Laravel.
旧版本 Laravel。
Model::all()->take(10)->get();
Newer version Laravel.
较新版本的 Laravel。
Model::all()->take(10);
For more reading consider these links:
如需更多阅读,请考虑以下链接:
回答by Luca C.
The simplest way in laravel 5 is:
Laravel 5 中最简单的方法是:
$listings=Listing::take(10)->get();
return view('view.name',compact('listings'));
回答by Amade
Another way to do it is using a limitmethod:
另一种方法是使用一种limit方法:
Listing::limit(10)->get();
This can be useful if you're not trying to implement pagination, but for example, return 10 random rows from a table:
如果您不尝试实现分页,这会很有用,但例如,从表中返回 10 个随机行:
Listing::inRandomOrder()->limit(10)->get();

