我想检索插入到表中的最后一个文件。我知道方法first()存在,并为您提供表中的第一个文件,但我不知道如何获得最后一个插入。
当前回答
请注意,如果您正在寻找顺序的或事件/有序的记录,last()、latest()是不确定的。最后/最近的记录可以具有完全相同的created_at时间戳,而您返回的是哪一个不是确定的。所以做orderBy(id|foo)->first()。欢迎其他关于如何确定的想法/建议。
其他回答
如果你正在寻找你刚刚用Laravel 3和4插入的实际行,当你在一个新模型上执行保存或创建操作时,如下所示:
$user->save();
-or-
$user = User::create(array('email' => 'example@gmail.com'));
然后将返回插入的模型实例,并可用于进一步的操作,例如重定向到刚刚创建的用户的配置文件页面。
在小容量系统上查找最后插入的记录几乎可以一直工作,但如果您必须同时插入,您可能最终会查询到错误的记录。在需要更新多个表的事务系统中,这确实会成为一个问题。
你从来没有提到你是否使用Eloquent, Laravel的默认ORM。如果你是,让我们假设你想要获得一个User表的最新条目,通过created_at,你可能会这样做:
User::orderBy('created_at', 'desc')->first();
首先,它根据created_at字段逐级排序用户,然后获取结果的第一条记录。
这将返回User对象的一个实例,而不是一个集合。当然,为了使用这个替代方案,您必须有一个User模型,扩展Eloquent类。这听起来可能有点令人困惑,但它真的很容易开始,ORM真的很有帮助。
要了解更多信息,请查看官方文档,它非常丰富和详细。
很多答案,有些我不太同意。所以我将再次总结我的评论。
如果你刚刚创建了一个新对象。 默认情况下,当您创建一个新对象时,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。
请注意,如果您正在寻找顺序的或事件/有序的记录,last()、latest()是不确定的。最后/最近的记录可以具有完全相同的created_at时间戳,而您返回的是哪一个不是确定的。所以做orderBy(id|foo)->first()。欢迎其他关于如何确定的想法/建议。
使用模型::(user_id, user_id美元)- >最新()- >先()- > (); 它将只返回一条记录,如果没有找到,它将返回null。 希望这能有所帮助。
推荐文章
- 如何使用雄辩删除表中的所有行?
- 如何从一个查询插入多行使用雄辩/流利
- Laravel雄辩的《WHERE NOT IN》
- 自动删除Laravel (Eloquent ORM)中的相关行
- Laravel 5 -如何访问在视图存储上传的图像?
- Laravel用()消息重定向返回
- “质量分配”在Laravel中是什么意思?
- 登录后,Laravel重定向回原始目的地
- Laravel中使用雄辩的ORM进行批量插入
- Laravel PHP命令未找到
- 如何使用Laravel和Eloquent查询两个日期之间?
- 从Laravel 5中的另一个控制器访问控制器方法
- Laravel未知列'updated_at'
- 如何评论laravel .env文件?
- Laravel -创建模型,控制器和迁移在单一的工匠命令