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


当前回答

您将需要按照您现在正在排序的相同字段进行排序,但是降序。 举个例子,如果你有一个名为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 6中另一种奇特的方法。x(不确定,但必须适用于5。X也是):

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

你也可以访问字段:

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

您将需要按照您现在正在排序的相同字段进行排序,但是降序。 举个例子,如果你有一个名为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();

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

很多答案,有些我不太同意。所以我将再次总结我的评论。

如果你刚刚创建了一个新对象。 默认情况下,当您创建一个新对象时,Laravel将返回新对象。

$lastCreatedModel = $model->create($dataArray); 

dd($lastCreatedModel); // will output the new output
echo $lastCreatedModel->key; // will output the value from the last created Object

还有一种方法是将all()方法与(last()方法和first()方法结合起来而不附带条件。

非常糟糕!不要那样做!

Model::get()->last();` // the most recent entry
Model::all()->last();` // the most recent entry

Model::get()->first();` // the oldest entry
Model::all()->first();` // the oldest entry

Which is basically the wrong approach! You get() all() the records, and in some cases that can be 200,000 or more, and then pick out just one row. Not good! Imagine your site is getting traffic from Facebook and then a query like that. In one month that would probably mean the CO² emissions of a city like Paris in a year. Because the servers have to work unnecessarily hard. So forget this approach and if you find it in your code, replace it/rewrite it. Maybe you don't notice it with 100 data sets but with 1000 and more it can be noticeable.

非常好的是:

Model::orderBy('id', 'desc')->last(); // the most recent record
Model::latest('id')->first(); // the most recent record
Model::latest('id')->limit(1)->get(); // the most recent record
Model::orderBy('id', 'desc')->limit(1)->get(); // the most recent entry
Model::orderBy('id', 'desc')->first(); // the most recent entry

Model::orderBy('id', 'asc')->first(); // the oldest entry
Model::orderBy('id', 'asc')->limit(1)->get(); // the oldest entry
Model::orderBy('id', 'asc')->first(); // the oldest entry

如果在此上下文中使用orderBy,则应始终将主键用作基,而不是create_at。

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

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