TypeORM配置One to One关联时PostgreSQL报DataTypeNotSupportedError原因是什么
报错原因
你在Restaurant实体的restaurantType字段上同时使用了@Column()和@OneToOne()两个装饰器,这是错误的核心诱因:
@Column()的作用是将类字段映射为数据库的普通列,PostgreSQL不存在和你自定义的RestaurantType实体类对应的原生数据类型,TypeORM解析时无法匹配到合法的数据库类型,直接抛出类型不支持错误。@OneToOne这类关联关系装饰器本身已经内置了外键列的映射逻辑,不需要额外加@Column()声明。
修复方案
直接删除restaurantType字段上的@Column()装饰器即可,修改后的代码如下:
@Entity() class Restaurant { @PrimaryGeneratedColumn() id: number; @Column({ type: 'varchar', length: 1000, unique: true }) name: string; // 移除了多余的@Column()装饰器 @OneToOne(() => RestaurantType) @JoinColumn() restaurantType: RestaurantType; }
额外优化提示
你当前的RestaurantType实体还有两处可修正的问题:
createdAt字段的类型使用了time with time zone,该类型仅存储时间不存储日期,不符合创建时间的存储需求,建议改为timestamp with time zone。createdAt的默认值写为Date.now()会取代码编译时的固定时间作为默认值,建议改为() => 'NOW()'调用数据库的当前时间函数生成默认值。
修正后的RestaurantType代码参考:
@Entity() class RestaurantType { @PrimaryGeneratedColumn() id: number; @Column({nullable: false}) resturantType: string; @Column({ type: 'timestamp with time zone', default: () => 'NOW()' }) createdAt: Date; }
内容的提问来源于stack exchange,提问作者Jithin Zacharia
相关产品推荐
相关产品推荐

