mysql - 记录后立即访问存储在数据库表中的“最新”记录
问题描述
在 Laravel 中将最后一行记录到数据库表后,我可以通过调用latest()
查询在记录后立即安全地访问相同的记录数据吗?因为其他用户的交易可能同时发生,它可能真的不再是最后一条记录了?
编辑:
例如:
Public function StoreNotif($data){
auth()->user()->Notif()->create(store $data here..)
}
Public function SendNotif(){
$data="123";
$this->StoreNotif($data)
event(new Notification(stored Notif instance?));
}
解决方案
不,您不能依赖数据库从当前脚本返回记录。
该->latest()
方法将始终首先对具有最近created_at
日期的记录进行排序。
https://laravel.com/docs/6.x/queries#ordering-grouping-limit-and-offset
但是您没有提供任何代码或解释来说明为什么这是一个问题。如果你刚刚创建了一条新记录,为什么还需要再次查询呢?您应该已经可以访问模型的实例。
编辑:我做了一些编辑来演示如何将模型从控制器传递到评论中引用的事件。如果您需要更具体的帮助,请发布您的代码。
SomeController.php
function store()
{
$model = Model::create([
'some_data' => 1
]);
// fire an event with the newly created model
event(new SomeEvent($model));
dd($model);
}
------------------------
Model {
// ...
attributes: [
'id' => 101,
'some_data' => 1
'created_at' => '2019-10-06 12:48:01',
'updated_at' => '2019-10-06 12:48:01',
]
// ...
}
SomeEvent.php
<?php
namespace App\Events;
use App\Model;
use Illuminate\Queue\SerializesModels;
class SomeEvent
{
use SerializesModels;
public $model;
public function __construct(Model $model)
{
$this->model = $model;
// ...
}
}
编辑:根据您新添加的代码,您只需要将新模型传递回原始方法。你可以做这样的事情。
Public function StoreNotif($data)
{
// add a return statement
return auth()->user()->Notif()->create(store $data here..);
}
Public function SendNotif()
{
$data="123";
// store the returned data to a variable
$model = $this->StoreNotif($data);
// call the event with the model instance
event(new Notification(model));
}
推荐阅读
- awk - awk 搜索文件可能包含多个 id 条目
- reactjs - 如何将 Next.js 应用于使用 create-react-app 创建的 React 项目?
- performance - 在 kubernetes 上查找和设置应用程序资源限制/请求的最佳方法
- c# - 有没有办法反序列化异常对象?
- javascript - 需要从对象数组中提取超过 100,000 人的姓名
- jquery - 在 Selenium 中执行 jQuery
- c - GCC Wunused-variable 警告使用的变量
- ios - UIButton 影响 UICollectionViewCell 外观
- c# - 如何使用内置身份功能使用
- javascript - 如何使用 React 找到与锚点 onClick 匹配的 ID?