我有一个具有日期属性的实体
@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` ?
})
}
我在文档中找不到如何做到这一点。
我也想做一些事情,比如";从某一周找到CCD_ 2";或";从某个月找到CCD_ 3";
如果使用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',
},
});