Laravel: How to get last N entries from DB

孤人 提交于 2020-08-20 23:10:11

问题


I have table of dogs in my DB and I want to retrieve 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);

Thank you very much for any help :)


回答1:


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.




回答2:


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.




回答3:


Dogs::orderBy('created_at','desc')->take(5)->get();



回答4:


You may also try like this:

$recentPost = Article::orderBy('id', 'desc')->limit(5)->get();

It's working fine for me in Laravel 5.6




回答5:


You can pass a negative integer n to take the last n elements.

Dogs::all()->take(-5)

This is good because you don't use orderBy which is bad when you have a big table.




回答6:


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.



来源:https://stackoverflow.com/questions/24860973/laravel-how-to-get-last-n-entries-from-db

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!