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


当前回答

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

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

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

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

其他回答

老实说,这太令人沮丧了,我几乎不得不通过这里的所有答案来发现他们中的大多数都不是我想要的。事实上,我只想在浏览器中显示以下内容:

在我的表上创建的最后一行 只有一个资源

我并没有打算对一组资源进行排序,并以递减的方式排列列表,下面这行代码是我在Laravel 8项目中所使用的。

Model::latest()->limit(1)->get();

试试这个:

Model::latest()->get();

请注意,如果您正在寻找顺序的或事件/有序的记录,last()、latest()是不确定的。最后/最近的记录可以具有完全相同的created_at时间戳,而您返回的是哪一个不是确定的。所以做orderBy(id|foo)->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。

使用模型::(user_id, user_id美元)- >最新()- >先()- > (); 它将只返回一条记录,如果没有找到,它将返回null。 希望这能有所帮助。