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

时间:2017-12-21 07:08:09

标签: mongodb mongodb-query mongodb-php php-mongodb

我在表格 academicyearTbl 中的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";

然后不应该允许插入,因为表中已有数据,如第一个所述。

请帮助!!!

1 个答案:

答案 0 :(得分: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();

P.S。你的代码需要很多其他的重构