如何检查两个时间戳之间的范围是否与其他两个时间戳不重叠

How to check the range between two timestamps is not overlaping two other timestamps

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

post 数据如下所示:

    "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";
    }

}

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

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

  1. 新 post 时间戳之间的范围不与任何其他时间重叠,主要问题
  2. 新的 post publish_at 时间戳比 now() 大,我知道怎么做
  3. 新的 post unpublish_at 时间戳大于 publish_at 时间戳,我也知道怎么做

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

非常感谢。

检查很简单:

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

这将指示特定的 post $a 与特定的 post $b 不重叠。 请注意,我没有检查您提到的第二个和第三个条件,因为您认为它们之前已完成。您需要做的就是遍历所有尚未发布的 post 并检查它们中的每一个是否与新的 post.

没有冲突情况