php - MySQL + PHP - 查询相对格式日期

标签 php mysql laravel php-carbon

我有两个表:步骤流程

  • 步骤有很多流程。
  • steps 具有 relative_time(字符串)列。
  • 流具有 active_on(可为空、时间戳)列。

步骤relative_time存储relative formats它们的值类似于:“+1 年”、“+2 天”、“+30 天”等。

流程 active_on 在用户激活流程时设置,如下所示:“2017-12-30 00:00:00”。

每次我想知道何时过期时,我都会从数据库中选择它,然后在 PHP(Laravel, Carbon )中执行:

/**
 * @return null|Carbon
 */
public function getExpiresAtAttribute() 
{
    if (!$this->active_on) {
        return null;
    }

    // Access the relative time for step (for example: "+3 days").
    $relativeTime = $this->step->relative_time;

    // Adds the limit time to the activation date,
    // turning it possible to check when the current flow
    // will "expires". 
    return $this->active_on->modify($relativeTime);        
}

问题

在 PHP 中检查过期值很容易。问题是,现在我只需要直接从数据库中选择“过期”的流,并且我不知道使用这种方法是否可行。我怎样才能实现这个目标?

最佳答案

您可以在relative_time中存储天数,而不是php日期间隔。这样就可以查询:

SELECT * FROM flows, steps WHERE flows.step_id = step.id AND NOW() > ADDDATE(flows.active_on, steps.relative_time)

这样您的所有流量都会过期。

实际上不需要改变数据库结构。您可以创建一个迁移,将relative_time从dateinterval转换为天数(是一个字符串字段)。

foreach (Steps::all() as $step) {
    $step->update([
      'relative_time' => strtotime($step->relative_time,0)/(3600*24);
    ]);
}

然后你可以调整getExpiresAtAttribute:

/**
 * @return null|Carbon
 */
public function getExpiresAtAttribute() 
{
    if (!$this->active_on) {
        return null;
    }

    // Access the relative time for step (for example: "+3 days").
    $relativeTime = $this->step->relative_time;

    // Adds the limit time to the activation date,
    // turning it possible to check when the current flow
    // will "expires". 
    return $this->active_on->modify("+$relativeTime days");        
}

关于php - MySQL + PHP - 查询相对格式日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52425832/

相关文章:

php - 如何将数字格式化为具有固定精度和固定数量的整数位数?

XAMPP Windows 上的 Php Cron 作业

MySQL反向匹配

mysql - 将行值添加到单列MYSQL中

php - Laravel Throttle 第二次覆盖

php - Laravel Echo 在 Laravel 8-vujs "^2.5.17"版本中未接收 Pusher 事件

PHP/SQL 变量操作

php - 当 Code Igniter 中没有更新时,如何测试我的 MySQL 更新查询是否成功?

php - For 循环在 Laravel Controller 类中不起作用

php - Laravel 事件、监听器、作业、队列之间的区别