【问题标题】:QueryFailedError upon renaming primary key with TypeORM使用 TypeORM 重命名主键时出现 QueryFailedError
【发布时间】:2021-07-16 14:35:28
【问题描述】:

我正在构建一个 web 应用程序来管理带有 NestJSTypeORM 的调查。

我使用以下两个具有@OneToMany 关系的实体(一个调查可以有多个部分):

survey.entity.ts

import { Column, Entity, OneToMany, PrimaryGeneratedColumn } from 'typeorm';
import { SurveySection } from './surveysection.entity';

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

  @Column()
  name: string;

  @OneToMany(
    'SurveySection',
    (survey_section: SurveySection) => survey_section.survey,
    {
      onDelete: 'CASCADE',
      onUpdate: 'CASCADE',
    },
  )
  sections: Array<SurveySection>;
}

surveysection.entity.ts

import { Column, Entity, JoinColumn, ManyToOne, PrimaryGeneratedColumn } from 'typeorm';
import { Survey } from './survey.entity';

@Entity()
export class SurveySection {
  @PrimaryGeneratedColumn()
  survey_section_ID: number;

  @Column()
  position: number;

  @ManyToOne('Survey', (survey: Survey) => survey.sections)
  @JoinColumn({ name: 'survey_id' })
  survey: Survey;
}

这段代码运行良好。


但是,当我将 surveysection.entity.ts 中的 survey_section_ID 重命名为“survey_section_ID”以外的任何名称并在我的 ormconfig.json 中添加 synchronize: true 时,我收到错误消息:

QueryFailedError: Incorrect table definition; there can be only one auto column and it must be defined as a key

当我尝试将 survey_section_ID 重命名为“survey_section_id”(全部小写)时,我什至得到:

QueryFailedError: Duplicate column name 'survey_section_id'

我的问题是:

上面的代码在哪里依赖于surveysection.entity.ts 中的PrimaryGeneratedColumn 被命名为“survey_section_ID”,仅此而已?


编辑:

从应用程序中删除dist 目录并读取完全相同的实体后,一切正常。

【问题讨论】:

  • 感谢您的资源。还在为这个苦苦挣扎。阅读文档并更多地使用代码。当我删除surveysection.entity.ts 中的@JoinColumn() 并重命名PrimaryGeneratedColumn 时,它会抛出QueryFailedError: You can't delete all columns with ALTER TABLE; use DROP TABLE instead。然后我必须手动删除表survey_section 并反向重命名PrimaryColumn 以便再次连接到数据库。由于某种原因,相同的设置在section_question 没有QueryFailedError 的桌子上完美运行

标签: typescript nestjs typeorm


【解决方案1】:

更新

在尝试了很多东西之后,我注意到由于某种原因,survey_section 的 3 列会继续被TypeORM 重新创建,即使不再包含在代码中。
当从项目中完全删除surveysection.entity.ts并在数据库中删除表survey_section时,重新启动应用表survey_section后仍会再次出现在数据库中,并显示3列。
ormlogs.log显示它已删除并将上述 3 列读入表 survey_section
ormconfig.json 一直有 "synchronize": true

在从项目中删除整个 dist 目录并读取 surveysection.entity.ts 后,所讨论的完全相同的示例代码起作用了。

3 列之一是survey_section_ID。如果事实上这 3 列一直是在幕后添加的,那么没有其他自动生成的列可以添加到表中并且名为 survey_section_id 的列会导致重复名称是有意义的。

我不知道如何重现这一点,或者我只是错过了一些东西,但我会留下这个作为答案,以防有人也遇到这种情况。

【讨论】:

    猜你喜欢
    • 2018-08-13
    • 2021-11-10
    • 2020-10-07
    • 2021-09-24
    • 2021-08-14
    • 2021-08-17
    • 2020-12-08
    • 2019-02-03
    • 2017-09-21
    相关资源
    最近更新 更多