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


当前回答

Laravel集合有方法

Model::all() -> last(); // last element 
Model::all() -> last() -> pluck('name'); // extract value from name field. 

这是最好的办法。

其他回答

如果表有日期字段,这(User::orderBy('created_at', 'desc')->first();)是最好的解决方案,我认为。 但没有日期字段,Model::orderBy('id', 'desc')->first()->id;我相信这是最好的解决办法。

不要使用Model::latest()->first();因为如果你的集合有多行创建在同一时间戳(这将发生在你使用数据库事务DB::beginTransaction();和DB::commit())则返回集合的第一行,显然这不是最后一行。

假设id为11、12、13的行是使用transaction创建的,那么它们都将具有相同的时间戳,因此您将通过Model::latest()->first();id: 11的行。

试试这个:

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

对于拉拉维尔 8:

Model::orderBy('id', 'desc')->withTrashed()->take(1)->first()->id

结果的sql查询:

Model::orderBy('id', 'desc')->withTrashed()->take(1)->toSql()

从“时间表”中选择*按“id”排序

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

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

你也可以访问字段:

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