首页 > 解决方案 > 记录后立即访问存储在数据库表中的“最新”记录

问题描述

在 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?));

}

标签: mysqldatabaselaravel

解决方案


不,您不能依赖数据库从当前脚本返回记录。

->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));
}

推荐阅读