php - MySQL + PHP - 查询相对格式日期
问题描述
我有两个表:steps和flow。
- 步骤有很多流程。
- 步骤有
relative_time
(字符串)列。 - 流有
active_on
(nullable, timestamp) 列。
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 中很容易检查过期值。问题是现在我只需要直接从数据库中选择“过期”的流,我不知道是否可以使用这种方法。我怎样才能做到这一点?
解决方案
您可以在 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");
}
推荐阅读
- javascript - 如何将根容器添加到 NextJS?
- sql - Pivot - 如果行中有 Null,如何编写代码
- javascript - 教程或快速“如何”在循环中使用数字和字符串
- dropzone.js - 如何设置 Dropzone.js 上传多个并同时分块上传?
- hibernate - Java实体类中的布尔函数导致JSON NullPointerException
- apache-spark - 数据插入表时从 HiveHBaseTableOutputFormat 到 HiveOutputFormat 的类转换异常
- azure-active-directory - “系统分配”身份和应用程序注册“服务主体”之间的区别
- linux - sed 命令不起作用:观察到的 sed:不匹配的 '#'
- javascript - 在 Typescript/Javascript 中使用别名导出元素
- c# - 如何检测 Outlook-Mail 主题行中的正则表达式并自动超链接?