问题
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