【问题标题】:How to get current auto incremented value in this case?在这种情况下如何获取当前的自动递增值?
【发布时间】:2020-01-28 10:35:07
【问题描述】:

如图所示,时间为“left”的数据被插入到当前用户名称下的每个字段“left”中。这是因为在函数 logout() 中我通过他的 id 找到用户。但我想通过自动递增的“user_id”来称呼用户。我怎么能做到?

 public function logout() {
        $id = auth()->id();
        $info = \App\UserInfo::find($id);
        $info->left = now(); 
        $info->save(); 
        auth()->logout();
        session()->forget('name');
        session()->put('left',now());
        return redirect('/');
    }

如果有办法从 UserInfo 对象中获取此 $time 值,我们可以更新“左”列。

$info = \App\UserInfo::where('id', $id)
    -> where('joined', $time)->first();
    ->update(['left' => now()]);

无论如何,这是让它工作的路线。现在它插入而不覆盖其他值。

 $user_info = \App\UserInfo::where('user_id', $id)->latest()->first();

【问题讨论】:

    标签: database laravel


    【解决方案1】:

    通过 user_id 查找 UserInfo

    $info = \App\UserInfo::where('user_id', $id)->firstOrFail();
    

    请注意,如果很多用户登录和注销,您的表格将会变得很大,如果您想实现消息聊天应用程序的 last seen 功能,旧数据似乎不相关

    【讨论】:

    • 当我注销时,我看到此错误“从空值创建默认对象”。但是关于当前用户的记录出现在数据库中(字段'joined'和'left'具有相同的值等于'joined')。
    • 因为没有UserInfo的记录和认证的用户ID,我会更新我的答案并告诉我你是否得到404
    • 但是有当前用户的记录! (用户信息)在数据库中。我猜它只是不知道'user_id'。但为什么呢?
    • 是否返回404?
    • 那么记录不存在,代码运行正常,你的数据库损坏了,运行php artisan migrate:refresh --seed
    猜你喜欢
    • 2021-05-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-21
    • 2023-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多