如何在laravel mongodb雄辩的查询中将日期与mongodb iso日期进行比较? [英] How to compare date with mongodb iso date in laravel mongodb eloquent query?

查看:490
本文介绍了如何在laravel mongodb雄辩的查询中将日期与mongodb iso日期进行比较?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从日期大于给定日期的数据中获取记录.但是我在将日期与mongodb iso datetime进行比较时遇到问题.

I want to get record from data where date is greater than given date. But I am getting problem in comparing date with mongodb iso datetime.

目前,我正在获取Y-m-d格式的日期,我想在查询中进行比较,而mongodb中的日期则为2015-10-08T08:01:46.000Z格式.

Currently I am getting date in Y-m-d format which I want to compare in query and date in mongodb is in 2015-10-08T08:01:46.000Z format.

推荐答案

Laravel的Eloquent支持Carbon/DateTime对象而不是MongoDate对象,该对象在保存到数据库时会在内部转换为MongoDate对象.您可以在laravel中使用名为 Carbon 的日期处理程序包进行查询.

Laravel's Eloquent supports Carbon/DateTime objects instead of MongoDate objects which will be converted internally to MongoDate objects when saved to the database. You could use this date handling package in laravel called Carbon with your queries.

例如,如果要从用户数据中查询查询,其中mongodb日期时间字段created_at大于给定日期(例如今天的记录),请使用Carbon的

For example, if you want to query for records from Users data where a mongodb datetime field created_at is greater that a given date, say records from today, use Carbon's startOfDay() property:

$dt = Carbon::now()->startOfDay();
$users = User::where('created_at', '>', $dt)->get();

类似地,要执行数据范围查询,即查询特定月份(例如2015年10月)之间的记录,请使用 whereBetween 方法:

Similarly, to do a data range query i.e. query for records between a specific month, say October of 2015, use the whereBetween method:

$users = User::whereBetween(
             'created_at', array(
                 Carbon::createFromDate(2015, 10, 1),
                 Carbon::createFromDate(2015, 10, 31)
             )
         )->get();

另一种方法是使用 雄辩 您可以使用Carbon/DateTime对象而不是MongoDate对象.受 文档 的示例启发:

Another approach would be to use Eloquent which allows you to work with Carbon/DateTime objects instead of MongoDate objects. Example inspired from the docs:

<?php

use Jenssegers\Mongodb\Model as Eloquent;

class User extends Eloquent {

    use SoftDeletingTrait;

    /**
     * Collection for Model
     *
     * @var String
     */
    protected $collection = "users";

    /**
     * Connection for model
     *
     * @var type
     */
    protected $connection = 'mongodb';

    protected $dates = array('created_at');
}

可以让您执行以下查询:

Which allows you to execute queries like:

$users = User::where('created_at', '>', new DateTime('-1 day'))->get();

或者直接使用MongoDate对象,您可以尝试

Or natively using MongoDate objects, you could try

$start = new MongoDate(strtotime("2015-10-01 00:00:00"));
$stop = new MongoDate(strtotime("2015-10-31 00:00:00"));

$users = DB::collection('users')->whereBetween('created_at', array($start, $stop))->get();

这篇关于如何在laravel mongodb雄辩的查询中将日期与mongodb iso日期进行比较?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆