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

TypeORM迁移报错:DEFAULT表达式无法使用列引用问题求助

解决TypeORM「cannot use column reference in DEFAULT expression」错误

错误原因

你在createdAt和updatedAt字段的默认值配置中写了() => 'timestamp',数据库会将这个字符串识别为列名而非获取当前时间的函数,这就触发了「不能在默认表达式中使用列引用」的错误。

修复方案

方案1:使用数据库原生时间函数

根据你使用的数据库类型调整配置:

  • MySQL/MariaDB:
    将时间字段的配置修改为使用CURRENT_TIMESTAMP函数:

    import { Column, Entity, PrimaryGeneratedColumn } from "typeorm";
    
    @Entity('users')
    class User {
        @PrimaryGeneratedColumn('increment')
        id: number;
    
        @Column({type: 'varchar', length: 45})
        name: string;
    
        @Column({type: 'varchar', length: 45, unique: true})
        email: string
    
        @Column({type: 'boolean', default: false})
        admin: boolean;
    
        @Column({type: 'varchar', length: 120})
        password: string;
    
        // 修复createdAt
        @Column({ type: 'timestamp', default: () => 'CURRENT_TIMESTAMP' })
        createdAt: Date;
    
        // 修复updatedAt
        @Column({ type: 'timestamp', default: () => 'CURRENT_TIMESTAMP', onUpdate: 'CURRENT_TIMESTAMP' })
        updatedAt: Date;
    
        @Column({ type: 'timestamp', nullable: true })
        deletedAt?: Date | null;
    }
    
    export { User }
    
  • PostgreSQL:
    使用NOW()函数,且PostgreSQL不支持onUpdate属性,可改用触发器或TypeORM的自动更新装饰器:

    // 改用NOW()函数
    @Column({ type: 'timestamp', default: () => 'NOW()' })
    createdAt: Date;
    

方案2:使用TypeORM内置装饰器(推荐)

TypeORM提供了@CreateDateColumn和@UpdateDateColumn装饰器,会自动适配不同数据库的时间函数,无需手动编写表达式,代码更简洁:

import { Column, Entity, PrimaryGeneratedColumn, CreateDateColumn, UpdateDateColumn } from "typeorm";

@Entity('users')
class User {
    @PrimaryGeneratedColumn('increment')
    id: number;

    @Column({type: 'varchar', length: 45})
    name: string;

    @Column({type: 'varchar', length: 45, unique: true})
    email: string

    @Column({type: 'boolean', default: false})
    admin: boolean;

    @Column({type: 'varchar', length: 120})
    password: string;

    // 自动设置创建时间
    @CreateDateColumn({ type: 'timestamp' })
    createdAt: Date;

    // 自动更新修改时间
    @UpdateDateColumn({ type: 'timestamp' })
    updatedAt: Date;

    @Column({ type: 'timestamp', nullable: true })
    deletedAt?: Date | null;
}

export { User }

额外优化建议

  • 日期字段直接声明为Date类型即可,TypeORM会自动处理数据库与实体间的类型转换,无需Date | string
  • 如果需要实现软删除,可使用@DeleteDateColumn替代手动声明deletedAt字段

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 17:27:22