【问题标题】:How to check whether time limit already exist in table?如何检查表中是否已经存在时间限制?
【发布时间】:2018-06-03 19:39:31
【问题描述】:

我在表 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";

那么应该不允许插入,因为前面提到的表中已经有数据了。

请帮忙!!!

【问题讨论】:

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


    【解决方案1】:

    您应该将两个日期设置为\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();
    

    附:您的代码需要大量其他重构

    【讨论】:

    • 感谢您的回答......你的意思是我必须将日期转换为时间戳
    • $mongosd = new MongoDate(strtotime($this->startson)); $mongoed = new MongoDate(strtotime($this->endson));
    • 您需要有\MongoDB\BSON\UTCDateTime 用于在 MongoDB 中插入的日期
    • 是的,您需要以某种方式(通过使用时间戳或\DateTimeImmutable)生成\MongoDB\BSON\UTCDateTime 并将其存储在数据库中
    • 不知道你用的是什么版本的mongodb;使用系统上可用的任何类型
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-06-13
    • 2018-01-29
    • 1970-01-01
    • 2016-03-29
    • 2017-04-27
    • 2019-08-21
    相关资源
    最近更新 更多