【问题标题】:Laravel eloquent query based on a given timeLaravel 基于给定时间的雄辩查询
【发布时间】:2023-01-18 01:18:30
【问题描述】:

我有一个简单的任务清单,列出了今天需要在不同时间完成的任务。每个任务都有一个提醒/通知,需要在计划前 x 分钟发送。

简化迁移如下:

Schema::create('user_tasks', function (Blueprint $table) {
    $table->id();
    $table->string('name');
    $table->timestamp('time'); // The time for when the task has been planned, i.e. 10:00
    $table->string('minutes'); // The minutes before a reminder needs to be send, i.e. 30
    $table->timestamps();
});

我只想根据当前时间和给定任务的 minutes 查询到期提醒的任务。因此,例如,我有一个名为 sweep the floors 的任务,其分钟值为 30。这意味着,在任务到期前 30 分钟,我要发送提醒。

我可以查询所有任务,然后检查每个任务是否到期,但显然我只想查询到期提醒的任务。

到目前为止,这是我的查询:

$tasks = Task::whereTime('time', '<', Carbon::now()->addMinutes($task->minutes)->format('H:i'))->get();

显然 $task-&gt;minutes 不存在,该值在数据库中,但我不确定如何进行查询。任何指针?

【问题讨论】:

  • 不要将数字存储在字符串中,将时间存储在 TIME 而不是字符串中。这将使以后的事情变得更容易

标签: php laravel eloquent


【解决方案1】:

您需要比较列“时间”和当前时间 + 列“分钟”。所以基本上你需要比较 2 列。为此,如果 whereTime 你可以使用 whereRaw(),例如这样的东西:

$tasks = Task::whereRaw('time < DATE_ADD("' . now() . '", interval minutes minute)')->get();

DATE_ADD是一个 MySQL 函数,它将时间添加到它的第一个参数。

【讨论】:

    【解决方案2】:

    对我来说,最好的方法是将表架构重构为:

    $table->id();
    $table->string('name');
    $table->time('time'); // The time for when the task has been planned
    $table->integer('minutes'); // The minutes before a reminder
    $table->time('time_notification');//you can do the query only of this column
    $table->timestamps();
    

    所以你可以通过这个查询得到它们:

    $tasks = Task::whereTime('time_notification', '<=', Carbon::now()->format('H:i'))->get();
    

    【讨论】:

      猜你喜欢
      • 2018-01-26
      • 2021-07-23
      • 2017-11-11
      • 2018-11-18
      • 2023-04-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多