TypeORM:在迁移中定义关系

问题描述 投票:0回答:1

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

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

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

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

有人知道这可能是什么问题吗?

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

node.js sequelize.js typeorm typeorm-datamapper
1个回答
0
投票

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');
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.