Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeORM: Define relation in migration

Hi I'm reading TypeORM docs, and trying to implement relations like showed here Im trying to have History model that relates to every User, so that each user has multiple history

Im reading this & using that example:

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

But after try to implement it I get column userId on History model does not exist ??

Does anyone know what could be the problem ?

Im assuming I should add relation in migration file for my Model but I do not see any of that in documentation ?

like image 616
Loki Avatar asked Sep 08 '25 11:09

Loki


1 Answers

The queryRunner has a method called createForeignKey. In a migration file where you create a table it could look like this:

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');
  }
}
like image 68
Wannes Avatar answered Sep 11 '25 02:09

Wannes