You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

NestJS+TypeORM添加时间戳后关联查询优化方案咨询

解决NestJS+TypeORM中时间戳导致关联查询失效的问题

方法一:让TypeORM忽略时间戳字段的对比

在User实体的created_at和updated_at字段上,给@Column装饰器添加compare: false配置,这样当你用完整的User实体对象作为查询条件时,TypeORM会自动忽略这两个时间戳字段,只对比主键ID:

import { Column, Entity, PrimaryGeneratedColumn } from 'typeorm';

@Entity()
export class User {
  @PrimaryGeneratedColumn()
  id: number;

  // 其他业务字段...

  @Column({ 
    type: 'timestamp', 
    default: () => 'CURRENT_TIMESTAMP',
    compare: false // 关键配置:忽略该字段的查询对比
  })
  created_at: Date;

  @Column({ 
    type: 'timestamp', 
    default: () => 'CURRENT_TIMESTAMP',
    onUpdate: 'CURRENT_TIMESTAMP',
    compare: false // 关键配置:忽略该字段的查询对比
  })
  updated_at: Date;
}

配置完成后,你就可以继续使用where: { owner: user }的写法查询Savedforum表了。

方法二:更简洁的查询写法

如果不想修改实体配置,还有几种更简洁的写法替代{ owner: { id: user.id } }:

  • 直接使用主键值:TypeORM支持直接传入关联实体的主键值作为查询条件,写法更短:
const savedForums = await this.savedforumRepository.find({
  where: { owner: user.id }
});
  • 使用外键字段:如果你的Savedforum实体中显式定义了ownerId外键字段(或TypeORM自动生成了该字段),可以直接用外键字段查询:
const savedForums = await this.savedforumRepository.find({
  where: { ownerId: user.id }
});
  • QueryBuilder写法:虽然代码稍长,但灵活性更高,完全不受实体字段对比的影响:
const savedForums = await this.savedforumRepository
  .createQueryBuilder('savedforum')
  .where('savedforum.ownerId = :userId', { userId: user.id })
  .getMany();

内容的提问来源于stack exchange,提问作者Vahid Aslan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 00:21:26