php Laravel:如何从数据库中获取最后 N 个条目
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24860973/
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
Laravel: How to get last N entries from DB
提问by Jakub Kohout
I have table of dogs in my DB and I want to retrieve N latest added dogs
.
我的数据库中有狗表,我想检索N latest added dogs
.
Only way that I found is something like this:
我发现的唯一方法是这样的:
Dogs:all()->where(time, <=, another_time);
Is there another way how to do it? For example something like this Dogs:latest(5);
还有另一种方法吗?例如这样的事情Dogs:latest(5);
Thank you very much for any help :)
非常感谢您的任何帮助:)
回答by The Alpha
You may try something like this:
你可以尝试这样的事情:
$dogs = Dogs::orderBy('id', 'desc')->take(5)->get();
Use orderBy
with Descending
order and take the first n
numbers of records.
orderBy
与Descending
order 一起使用并获取第一个n
记录数。
回答by parker_codes
My solution for cleanliness is:
我的清洁解决方案是:
Dogs::latest()->take(5)->get();
It's the same as other answers, just with using built-in methods to handle common practices.
它与其他答案相同,只是使用内置方法来处理常见做法。
回答by Luca C.
Dogs::orderBy('created_at','desc')->take(5)->get();
回答by Bablu Ahmed
You may also try like this:
你也可以这样尝试:
$recentPost = Article::orderBy('id', 'desc')->limit(5)->get();
It's working fine for me in Laravel 5.6
它在 Laravel 5.6 中对我来说很好用
回答by lzoesch
Ive come up with a solution that helps me achieve the same result using the array_slice()
method. In my code I did array_slice( PickupResults::where('playerID', $this->getPlayerID())->get()->toArray(), -5 );
with -5
I wanted the last 5 results of the query.
我想出了一个解决方案,可以帮助我使用该array_slice()
方法获得相同的结果。在我的代码中array_slice( PickupResults::where('playerID', $this->getPlayerID())->get()->toArray(), -5 );
,-5
我想要查询的最后 5 个结果。
回答by Jo?o Marcus
You can pass a negative integer n to take the last n elements.
您可以传递一个负整数 n 来获取最后 n 个元素。
Dogs::all()->take(-5)
This is good because you don't use orderBy which is bad when you have a big table.
这很好,因为您不使用 orderBy,这在您有一张大桌子时会很糟糕。