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` ?
})
}

我在文档中找不到如何做到这一点。

我也想做一些事情,比如";从某一周找到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',
},
});

最新更新