如何检查表中是否已存在时间限制?

问题描述 投票:1回答:1

我在mongodb数据库中有很多记录,在学术界就像

 "_id": ObjectId("5a3b41581d78593809000029"),
 "academicyear_id": 67,
  "academicyearname": "2017",
  "startson"▼: "01/01/2017",
  "endson": "12/31/2017",
  "graceperiod": "12/14/2017",
 "status": "active", 

我想调整下面的代码

码:

      class settingsModel
      {
      function testcode()
      {
      $this->collection = $this->db->academicyearTbl;
      $query4 = array('startson'=> $this->startson,'endson' => $this->endson);
      $count4 = $this->collection->find($query4)->count();
      if($count4 > 0)
      {
        //show message
      }
      else
      {
         // allow inserting the new record
      }
      }
      }
      $foo = new settingsModel();
      $foo->academicyearname ="2018"
      $foo->startson="06/02/2017";
      $foo->endson="12/01/2017";
      $foo->testcode();

我是mongodb的新手,我能够获得任何灵感来比较输入的新开始日期和结束日期是否应该落入数据库中已有的时间段。

例如,如果用户将输入新数据,例如

      $foo->academicyearname ="2018"
      $foo->startson="06/02/2017";
      $foo->endson="12/01/2017";

然后不应该允许插入,因为第一个中提到的表中已有数据。

请帮忙 !!!

mongodb mongodb-query mongodb-php php-mongodb
1个回答
0
投票

您应该将两个日期设置为\DateTimeImmutable,然后在检查间隔时可以使用$gt$lt运算符作为MongoDate(已过时),如下所示:

class settingsModel
{
    function testcode()
    {
      $this->collection = $this->db->academicyearTbl;

      $query4 = array(
         'startson'=> array( 
            '$gt' => new MongoDate( $this->startson ),
         ),
         'endson' =>  array( 
            '$lt' => new MongoDate( $this->endson ),
         ),
      );

      $count4 = $this->collection->find($query4)->count();
      if($count4 > 0)
      {
        //show message
      }
      else
      {
         // allow inserting the new record
      }
  }
} 

$foo = new settingsModel();
$foo->academicyearname ="2018";
$foo->startson = strtotime("2017-02-06"); //notice the date format
$foo->endson = strtotime("2017-01-12"); //notice the date format
$foo->testcode();

附:你的代码需要很多其他的重构

© www.soinside.com 2019 - 2024. All rights reserved.