首页 > 解决方案 > TypeORM:定义迁移中的关系

问题描述

嗨,我正在阅读 TypeORM 文档,并尝试实现此处所示的关系 我试图拥有与每个用户相关的历史模型,以便每个用户都有多个历史记录

我正在阅读并使用该示例:

https://github.com/typeorm/typeorm/blob/master/docs/many-to-one-one-to-many-relations.md

但是在尝试实现它之后,我得到历史模型上的 userId 列不存在?

有谁知道可能是什么问题?

我假设我应该在我的模型的迁移文件中添加关系,但我在文档中没有看到任何内容?

标签: node.jssequelize.jstypeormtypeorm-datamapper

解决方案


queryRunner 有一个名为createForeignKey. 在您创建表的迁移文件中,它可能如下所示:

export class ExampleMigration implements MigrationInterface {
  public async up(queryRunner: QueryRunner): Promise<any> {
    await queryRunner.createTable(
      new Table({
        name: 'stuff',
        columns: [
          {
            name: 'id',
            type: 'uuid',
            isPrimary: true
          },
          {
            name: 'userId',
            type: 'uuid'
          }
        ]
      })
    );

    await queryRunner.createForeignKey(
      'stuff',
      new TableForeignKey({
        columnNames: ['userId'],
        referencedTableName: 'users',
        referencedColumnNames: ['id']
      })
    );
  }

  public async down(queryRunner: QueryRunner): Promise<any> {
    await queryRunner.dropTable('userSessions');
  }
}

推荐阅读