【问题标题】:Searching data older than a Date with typeORM使用 typeORM 搜索早于日期的数据
【发布时间】:2018-11-27 08:45:05
【问题描述】:

我正在执行对 Postgre DB 的查询,以获取早于特定日期的数据。

这是我的功能

async filesListToDelete(): Promise<any> {
  return await this.fileRepository.find({
    where: { last_modified: { $lt: '2018-11-15 10:41:30.746877' } },
  });
}

这是我定义文件实体的方式:

export class File {
  @PrimaryGeneratedColumn()
  id: number;

  @Column({ nullable: false })
  idFonc: number;

  @Column({ nullable: false })
  version: number;

  @Column('varchar', { length: 100, nullable: false })
  filename: string;

  @Column({ nullable: true })
  last_modified: Date;

  @Column({ nullable: false })
  device: boolean;

  @ManyToOne(type => Type, { nullable: false })
  @JoinColumn({ referencedColumnName: 'id' })
  type: Type;

  @OneToMany(type => FileDevice, filedevice => filedevice.file)
  fileDevice: FileDevice[];
}

我收到这个错误

QueryFailedError: invalid input syntax for type timestamp: "{"$lt":"2018-11-15 10:41:30.746877"}"

【问题讨论】:

    标签: database mongodb postgresql typeorm typeorm-activerecord


    【解决方案1】:

    您可以使用 MoreThan,doc

    async filesListToDelete(): Promise<any> {
      return await this.fileRepository.find({
       where: { 
           last_modified:  MoreThan('2018-11-15  10:41:30.746877') },
    });}
    

    【讨论】:

    • 抱歉,他们不是在寻找 LessThan b/c 他们在寻找比该日期更旧的数据吗? (而且 MoreThan 会返回更新的数据?)
    【解决方案2】:

    您也可以使用createQueryBuilder 执行此操作,如下所示:

        public async filesListToDelete(): Promise<any> {
            let record = await this.fileRepository.createQueryBuilder('file')
                .where('file.last_modified > :start_at', { start_at: '2018-11-15  10:41:30.746877' })
                .getMany();
    
            return record
        }
    

    【讨论】:

      【解决方案3】:

      其中任何一个都将获取 OLDER 数据

      带有内置 TypeORM 运算符 (docs)

      async filesListToDelete(): Promise<any> {
        return await this.fileRepository.find({
          where: { last_modified:  LessThan('2018-11-15  10:41:30.746877') },
        });
      }
      

      使用PostgreSQL 运算符 (docs)

      public async filesListToDelete(): Promise<any> {
          let record = await this.fileRepository.createQueryBuilder('file')
              .where('file.last_modified < :start_at', { start_at: '2018-11-15  10:41:30.746877' })
              .getMany();
      
          return record
      }
      

      【讨论】:

        猜你喜欢
        • 2013-02-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-12-09
        相关资源
        最近更新 更多