1

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

@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从某个月份查找”之类的事情

4

1 回答 1

1

如果使用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',
  },
});
于 2021-04-20T19:15:47.797 回答