我想检索插入到表中的最后一个文件。我知道方法first()存在,并为您提供表中的第一个文件,但我不知道如何获得最后一个插入。


当前回答

Laravel 6中另一种奇特的方法。x(不确定,但必须适用于5。X也是):

DB:表(your_table) - > () - > ();

你也可以访问字段:

DB:表(your_table) - > () - > () - > id;

其他回答

要获得最后的记录细节,使用下面的代码:

Model::where('field', 'value')->get()->last()

您将需要按照您现在正在排序的相同字段进行排序,但是降序。 举个例子,如果你有一个名为upload_time的上传时间戳,你可以这样做;

Pre-Laravel 4

return DB::table('files')->order_by('upload_time', 'desc')->first();

Laravel 4及以上版本

return DB::table('files')->orderBy('upload_time', 'desc')->first();

适用于Laravel 5.7及以上版本

return DB::table('files')->latest('upload_time')->first();

这将按上传时间、降序对文件表中的行进行排序,并选择第一个。这将是最新上传的文件。

使用pdo,我们可以得到文档中最后插入的id PDO lastInserted

过程

use Illuminate\Support\Facades\DB;
// ...
$pdo = DB::getPdo();
$id = $pdo->lastInsertId();
echo $id;

你只需要检索数据并反转它们,你就会得到你想要的记录,让我解释laravel 9的代码

return DB::table('files')->orderBy('upload_time', 'desc')->first();

如果你不愿意。x的最后结果

 return DB::table('files')->orderBy('upload_time', 'desc')->limit(x)->get();

你可以使用eloquent来使用这个函数:

模型::最新的()- > (1)- > ();