【问题标题】:Query database for a countdown timer查询数据库以获取倒数计时器
【发布时间】:2014-09-29 18:48:26
【问题描述】:

我正在使用 Laravel,我有一个包含两个表的数据库:在第一个表中有一个包含整数字段的列,我想像计时器一样工作,在第二个表中我存储用户提交一个表单,并且有一个带有提交时间的时间戳。 我会阻止用户在第一个表中的字段指定的时间到期之前提交相同的表单。 我该怎么做?

这是控制器中的代码:

public function getShow($id = null){
  if ( ! is_null($id)){
     $submitted = Actionshistory::where('action_id','=',$id)->first()->created_at;
     $minutes = Actions::where('id','=',$id)->pluck('time_need'); // time need between submit two same form.
     $passed = Carbon::createFromTimeStamp($submitted)->diffInMinutes(Carbon::now('Europe/Rome'));
        if ($submitted && $passed >= $minutes)
        {
         // Other queries and success message
        }
         // Error message
        }
         // error message for id
}

我需要使用Carbon::now('Europe/Rome')

谢谢。

【问题讨论】:

    标签: php mysql database laravel timestamp


    【解决方案1】:

    创建一个隐藏的输入,其中将包含提供表单的时间。

    Form::hidden('time_served', Carbon::now());
    

    您需要在表单的 onsubmit 事件中使用 ajax 来检查时间是否有效并返回 true 或 false,这将停止或让表单提交继续。

    javascript 看起来像...

    $(document).ready(function() {
        $('#MyForm').on('submit', function(e) {
            $.getJSON('some/route', {}, function(data, textStatus) {
                if(data.success) {
                    return true;
                } else {
                    alert(data.message);
                    return false;
                }
            });
        });
    });
    

    现在返回 json 的 some/route 路由看起来类似于...

    Route::get('some/route', function()
    {
        $time_served = Input::get('time_served');
        $difference = Carbon::createFromTimeStamp($time_served)->diffInSeconds(Carbon::now());
        $seconds_allowed = Config::get('timers.seconds');  // However you get your "timer"
    
        if($seconds_allowed > $difference) {
            return Response::json(array('success' => true, 'message' => 'Time requirement met.'));
        } else {
            return Response::json(array('success' => false, 'message' => 'Time requirement not met.'));
        }
    
    });
    

    【讨论】:

    • 我试过了,但调试器总是说“DateTime::setTimestamp() 期望参数 1 很长,给定对象”
    【解决方案2】:

    没有看到您的代码,就没有具体的答案。下面是一些帮助您入门的内容:

    $submitted = Actionshistory::where('action_id', $id)->first()->created_at;
    $interval  = Actions::where('id','=',$id)->pluck('time_need');
    
    if ($submitted->diffInMinutes(Carbon::now()) < $interval)
    {
        // throw your error or whatnot
    }
    

    【讨论】:

    • 调试器说“DateTime::setTimestamp() 期望参数 1 很长,给定对象”
    • @aptscript - 只要您不向我们展示您正在使用的所有代码,我们就无法为您提供更多帮助。
    • @aptscript - 这是因为 $submitted 已经是一个 Carbon 实例。我更新了我的答案。
    • 它似乎不起作用,但它没有显示任何调试错误。
    猜你喜欢
    • 2014-04-15
    • 2018-07-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多