TypeORM 时间戳日期相等性不起作用
TypeORM Timestamp Date equality not working
我将 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
Returns 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" = LIMIT 1 -- PARAMETERS: ["2022-02-19T22:10:13.564Z"]
似乎 TypeORM 没有将 JavaScript Date
对象转换为正确的 PostgreSQL timestamp
格式。数据库中的时间戳看起来像2022-02-19 22:10:13.564432
,这是一种完全不同的格式,精度更高。
在使用 TypeORM 时,我应该以特定的方式进行 timestamp
相关搜索吗?
注意:我也试过寻找有同样问题的人,但我没有看到任何明确的解决方案。我正在尝试围绕创建日期实现基于游标的分页,但是大于和小于运算符也不能正常工作。
我最近 运行 遇到了同样的问题,并通过将 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;
}
我将 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
Returns 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" = LIMIT 1 -- PARAMETERS: ["2022-02-19T22:10:13.564Z"]
似乎 TypeORM 没有将 JavaScript Date
对象转换为正确的 PostgreSQL timestamp
格式。数据库中的时间戳看起来像2022-02-19 22:10:13.564432
,这是一种完全不同的格式,精度更高。
在使用 TypeORM 时,我应该以特定的方式进行 timestamp
相关搜索吗?
注意:我也试过寻找有同样问题的人,但我没有看到任何明确的解决方案。我正在尝试围绕创建日期实现基于游标的分页,但是大于和小于运算符也不能正常工作。
我最近 运行 遇到了同样的问题,并通过将 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;
}