如何解决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',});
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。