Laravel: 如何从 DB 获取最后 N 个条目

我有表的狗在我的数据库,我想恢复 N latest added dogs

我找到的唯一方法是这样的:

Dogs:all()->where(time, <=, another_time);

还有其他的方法吗? 例如像这样的 Dogs:latest(5);

非常感谢您的帮助:)

115082 次浏览

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.

Update (Since the latest method has been added):

$dogs = Dogs::latest()->take(5)->get();
Dogs::orderBy('created_at','desc')->take(5)->get();

You may also try like this:

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

It's working fine for me in Laravel 5.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.

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.

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.

The Alpha's solution is very elegant, however sometimes you need to re-sort (ascending order) the results in the database using SQL (to avoid in-memory sorting at the collection level), and an SQL subquery is a good way to achieve this.

It would be nice if Laravel was smart enough to recognise we want to create a subquery if we use the following ideal code...

$dogs = Dogs::orderByDesc('id')->take(5)->orderBy('id')->get();

...but this gets compiled to a single SQL query with conflicting ORDER BY clauses instead of the subquery that is required in this situation.

Creating a subquery in Laravel is unfortunately not simply as easy as the following pseudo-code that would be really nice to use...

$dogs = DB::subQuery(
Dogs::orderByDesc('id')->take(5)
)->orderBy('id');

...but the same result can be achieved using the following code:

$dogs = DB::table('id')->select('*')->fromSub(
Dogs::orderByDesc('id')->take(5)->toBase(),
'sq'
)->orderBy('id');

This generates the required SELECT * FROM (...) AS sq ... sql subquery construct, and the code is reasonably clean in terms of readability.)

Take particular note of the use of the ->toBase() function - which is required because fromSub() doesn't like to work with Eloquent model Eloquent\Builder instances, but seems to require a Query\Builder instance). (See: https://github.com/laravel/framework/issues/35631)

I hope this helps someone else, since I just spent a couple of hours researching how to achieve this myself. (I had a complex SQL query builder expression that needed to be limited to the last few rows in certain situations).

Imagine a situation where you want to get the latest record of data from the request header that was just inserted into the database:

$noOfFilesUploaded = count( $request->pic );// e.g 4
$model = new Model;


$model->latest()->take($noOfFilesUploaded);

This way your take() helper function gets the number of array data that was just sent via the request.

You can get only ids like so:

$model->latest()->take($noOfFilesUploaded)->puck('id')

For getting last entry from DB

$variable= Model::orderBy('id', 'DESC')->limit(1)->get();

I use it this way, as I find it cleaner:

$covidUpdate = COVIDUpdate::latest()->take(25)->get();
use DB;


$dogs = DB::select(DB::raw("SELECT * FROM (SELECT * FROM dogs ORDER BY id DESC LIMIT 10) Var1 ORDER BY id ASC"));
Dogs::latest()->take(1)->first();

this code return the latest record in the collection

Can use this latest():

$dogs = Dogs::latest()->take(5)->get();