MikroORM:如何按日或月而不是完整日期查询日期属性?

问题描述

我有一个具有日期属性的实体

@Entity()
export class Foo {
    // ...other properties

    @Property({ type: DateType })
    date = new Date()
}

我想进行查询以查找来自某个特定日期的所有 Foo

例如

async getByDate(someDate: Date) {
    const foo = await this.repository.find({
        // What should go to get Foo from the same day as `someDate` ?
    })
}

我在文档中找不到如何操作。

我还想做诸如“从某个星期查找 Foo”或“从某个月份查找 Foo”之类的操作

解决方法

如果使用 DateType,则是将其映射到 Date 对象,因此应按 Date 对象进行查询。 Date 对象的时间部分将被截断 - 这发生在 DateType 中,因此请随时检查其源代码,它非常直接。

const users = await em.find(User,{ date: new Date('2020-05-20') });

https://github.com/mikro-orm/mikro-orm/blob/master/packages/core/src/types/DateType.ts

从实现中您还可以看到,实际上它也支持按字符串查询,因此这也能正常工作:

const users = await em.find(User,{ date: '2021-04-20' });

要过滤一整周,您需要先找到一周的开始和结束时间(将为您保留),并使用 $gte$lt 运算符的组合:

const users = await em.find(User,{
  date: {
    $gte: new Date('2021-04-19'),$lt: new Date('2021-04-25'),},});


// or with strings

const users = await em.find(User,{
  date: {
    $gte: '2021-04-19',$lt: '2021-04-25',});