我有两个表:步骤和流程。
- 步骤有很多流程。
- 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/