1

mongodb在表AcademicyearTbl中的数据库中有很多记录,例如

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

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

请帮忙 !!!

4

1 回答 1

0

您应该将两个日期设置为\DateTimeImmutable ,然后在检查间隔时可以使用$gtand$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();

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

于 2017-12-21T08:13:25.933 回答