我正在使用 TypeORM 和一个看起来像这样的实体:
@Entity('users')
export class UserEntity extends BaseEntity {
@PrimaryColumn()
id: string;
@CreateDateColumn({ type: 'timestamp' })
createdAt: Date;
@UpdateDateColumn({ type: 'timestamp' })
updatedAt: Date;
}
但是,当我尝试使用 TypeORM 实体的存储库执行任何类型的 timestamp
等式相关 SQL 查询时,它无法正常工作。例如查询:
const id = 'dbe9e81d-aefa-459d-8460-707ade0fa156';
const userEntity = userRepository.findOne(id); // UserEntity(...)
const sameUserEntity = userRepository.findOne({ where: { createdAt: userEntity.createdAt } }); // undefined
为userEntity
返回正确的实体,为sameUserEntity
返回未定义的实体。我查看了 TypeORM 为该查询构建的日志,它看起来像这样:
SELECT "UserEntity"."id" AS "UserEntity_id",
"UserEntity"."created_at" AS "UserEntity_created_at",
"UserEntity"."updated_at" AS "UserEntity_updated_at"
FROM "users" "UserEntity"
WHERE "UserEntity"."created_at" = $1 LIMIT 1 -- PARAMETERS: ["2022-02-19T22:10:13.564Z"]
TypeORM 似乎没有将 JavaScript Date
对象转换为正确的 PostgreSQL timestamp
格式。数据库中的时间戳看起来像2022-02-19 22:10:13.564432
,这是完全不同的格式,并且精度更高。
使用 TypeORM 时,我应该以特定的方式进行与时间戳相关的搜索吗?
注意:我也尝试过寻找有同样问题的人,但我没有看到任何明确的解决方案。我正在尝试围绕创建日期实现基于游标的分页,但是大于和小于运算符也无法正常工作。
最佳答案
我最近遇到了同样的问题,并通过向列装饰器添加 precision: 3
来修复它。请注意,这是基于您一开始就不需要这种精度级别的假设。
@Entity('users')
export class UserEntity extends BaseEntity {
@PrimaryColumn()
id: string;
@CreateDateColumn({
type: 'timestamp',
precision: 3
})
createdAt: Date;
@UpdateDateColumn({
type: 'timestamp',
precision: 3
})
updatedAt: Date;
}
关于javascript - TypeORM 时间戳日期相等不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71189866/