且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在laravel mongodb雄辩的查询中将日期与mongodb iso日期进行比较?

更新时间:2023-01-16 08:23:02

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();