【问题标题】:Why does yii2 mongodb date filter returns no results when using between condition为什么yii2 mongodb日期过滤器在使用条件之间时没有返回结果
【发布时间】:2017-06-19 07:57:38
【问题描述】:

我正在使用 yii2 mongodb 最新版本,当我尝试在给定日期范围内获取记录时,我得到空记录。我的代码如下

在我的模型中过滤今天收到的记录的功能

 public function today(){
    $finder = self::find();        
    $startDay = strtotime('midnight',time())-1;//start of day
    $endDay   = time(); //now
    $d1=to_isoDate($startDay);
    $d2=to_isoDate($endDay);         
    $args=['created_at'=>['$gte'=>$d1,'$lte'=>$d2]]; 

    $finder->andWhere($args);
    return $finder;
  }

将时间戳转换为 UTCDateTime 的函数,当插入到集合或创建查询时,我调用此函数

function to_isoDate($timestamp){
   return new \MongoDB\BSON\UTCDateTime($timestamp);
}

尝试获取今天创建的所有模型什么都没有返回,但我有当天的记录 其中一份mongo文件如下

{ 
"_id" : ObjectId("5892deb01c80f22a180af457"), 
"title" : "TEST", 
"content" : "we are", 
"slug" : "test", 
"guid" : "5892deae76036", 
"type" : "sms_outbox", 
"mime" : ObjectId("5891ae441c80f24e4057f332"), 
"meta" : {
    "from" : "5891d0a51c80f2131d327b92", 
    "scheduled" : "0"
}, 
"alias" : "+254723681977", 
"parent" : "5891ae071c80f2394e688db5", 
"status" : "sent", 
"created_at" : ISODate("2017-01-01T07:24:30.000+0000"), 
"updated_at" : ISODate("2017-02-02T07:24:30.000+0000"), 
"updated_by" : "588899ac1c80f227512d1102", 
"created_by" : "588899ac1c80f227512d1102"
}

请协助解决问题所在

【问题讨论】:

    标签: mongodb yii2 yii2-model php-mongodb


    【解决方案1】:

    我今天遇到了类似的问题,将 $timestamp 乘以 1000 解决了这个问题,并且日期过滤器现在可以正常工作。

    这里是修改后的to_isoDate方法:

    function toIsoDate($timestamp){
       return new \MongoDB\BSON\UTCDateTime($timestamp * 1000);
    }
    

    您还需要将查询修改为如下所示:

    public function today(){
        $finder = self::find();        
        $startDay = strtotime('midnight',time())-1;//start of day
        $endDay   = time(); //now
        $d1= toIsoDate($startDay);
        $d2= toIsoDate($endDay);         
        $finder->andWhere(['>=', 'created_at', $d1]);
        $finder->andWhere(['<=', 'created_at', $d2]);
        return $finder;
    }
    

    参考:https://github.com/yiisoft/yii2-mongodb/issues/181

    我希望这对某人有所帮助,我花了很长时间试图找到解决方案。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-12-06
      • 2023-03-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-06
      • 2010-09-30
      相关资源
      最近更新 更多