【问题标题】:How to check the range between two timestamps is not overlaping two other timestamps如何检查两个时间戳之间的范围不与其他两个时间戳重叠
【发布时间】:2020-07-26 07:31:30
【问题描述】:

我将 laravelmongodb 一起使用,在数据库中存储新数据时遇到了重叠问题。我想为用户设置此功能以在数据库中存储新帖子并设置一个计时器,以便帖子在请求的时间戳发布,并在未来的特定时间戳中删除。一切都经过管理和测试,但唯一的问题是重叠。

帖子数据如下所示:

    "title" : "Some title",
    "body"  : [ dummy body data ... ],
    "tags"  : [ some tags here ...],
    "publish_at"   : "1595740000", //timestamp
    "unpublish_at" : "1595741111"  //timestamp

我将数据存储在数据库中:

 /**
 * Store a newly created resource in storage.
 *
 * @param StoreRequest $request
 * @return \Illuminate\Http\JsonResponse
 */
public function store(StoreRequest $request)
{
    $data = $request->validated();

    #Here I want to do the validation of timestamps
    #Using Post::all() I can access all of the posts in the database

    $count = Post::where('name', $data['name'])->count();
    if ($count !== 0) {
        // just a sample validation
        return 'name_already_exists';
    } else {
        Post::Create([
            "title" => $data['title'],
            "body" => $data['body'],
            "tags" => $data['tags'],
            "is_active" => true,
            "publish_at" => Carbon::parse($data['publish_at'])->timestamp,
            "unpublish_at" => Carbon::parse($data['unpublish_at'])->timestamp,
        ]);
        return "resource created";
    }

}

一切看起来都不错!但是,如果用户添加不同的帖子以供将来发布和未发布,我需要检查新的帖子时间戳,以免与数据库中的任何其他帖子时间戳重叠。

到目前为止,我想我必须在这里检查 3 个条件,

  1. 新发布的时间戳之间的范围不重叠,主要问题
  2. 新帖子 publish_at 时间戳比 now() 大,我知道该怎么做
  3. 新帖子 unpublish_at 时间戳大于 publish_at 时间戳,我也知道该怎么做

Laravel 版本为 6.18,Mongodb ORM 包为Jenssegers/Mongodb,与 eloquent ORM 非常相似,同时安装了 Carbon 包。

非常感谢。

【问题讨论】:

  • 请在询问 SO 之前编写您尝试解决问题的代码
  • publish_atunpublish_at的格式是什么?
  • @STA 它们都是 Int32 / 时间戳

标签: php laravel mongodb timestamp php-carbon


【解决方案1】:

检查很简单:

if($a->publish_at > $b->unbublish_at || $a->unpublish_at < $b->publish_at)
    return true;

这将表明特定帖子 $a 不与特定帖子 $b 重叠。 请注意,我没有检查您提到的第二个和第三个条件,因为您之前考虑过它们。您需要做的只是遍历尚未发布的帖子,并检查每个帖子是否与新帖子发生冲突。

【讨论】:

  • 谢谢,在 eloquent 上调用的 all() 方法返回一个数据集合,因此访问集合中的每个数据是的痛苦,所以你建议我在这里使用 foreach 循环进行此验证?
  • 实际上,当您考虑它时,您并不需要循环。让数据库做这项工作。运行一个查询,其中 publish_at 或 unpublish_at 时间戳在 mongo 记录时间戳之间,或者 mongo 记录时间戳都在新的 publish_at 和 unpublish_at 时间戳内。这将为您提供来自 mongo 的所有记录,这些记录将部分或全部重叠。如果结果为空(没有记录),那么你就可以去
猜你喜欢
  • 2021-09-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-13
  • 2022-01-23
  • 2020-11-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多