首页 > 解决方案 > MySQL + PHP - 查询相对格式日期

问题描述

我有两个表:stepsflow

Stepsrelative_time存储相关格式,其值类似于:“+1 年”、“+2 天”、“+30 天”等。

Flowsactive_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 中很容易检查过期值。问题是现在我只需要直接从数据库中选择“过期”的流,我不知道是否可以使用这种方法。我怎样才能做到这一点?

标签: phpmysqllaravelphp-carbon

解决方案


您可以在 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");        
}

推荐阅读