Migrations of Manytomany relations on Typeorm using Queryrunner

Asked

Viewed 310 times

0

It is possible to create the SQL of an Migration automatically, through the CLI command migration:generate -n MigrationName?

However, it is possible to create Migrations from Migration API, more readable than pure SQL.

Example

Entities

@Entity('students')
class Student {
   @PrimaryGeneratedColumn('uuid')
   id: string;

   @Column()
   name: string;
}

@Entity('classes')
class Class {
   @PrimaryGeneratedColumn('uuid')
   id: string

   @Column()
   name: string;
   
   @ManyToMany(() => Student)
   @JoinTable()
   students: Student[];
}

The problem is in creating relationships Manytomany with the Migration API, which is not described in the documentation.

Migration of Class using Migration API, without the relationship Manytomany

export class CreateClass implements MigrationInterface {

    async up(queryRunner: QueryRunner): Promise<void> {
        await queryRunner.createTable(new Table({
            name: 'classes',
            columns: [
                {
                    name: 'id',
                    type: 'uuid',
                    isPrimary: true,
                    generationStrategy: 'uuid',
                    default: 'uuid_generate_v4()'
                },
                {
                    name: 'id',
                    type: 'varchar'
                }
            ],
        }))
    }
}

How to create this Migration with the Manytomany relationship using Queryrunner?

1 answer

0


Creating the Relationship Tables

The best way to create this relationship is by describing the intermediate table of the Manytomany relation, using the Queryrunner.

It is important to pay attention to nomenclatures table and fields, so that they are compatible with what Typeorm would generate in SQL.

Therefore, simply add the relationship table Manytomany, afterward of the creation of the table described in the question example.

await queryRunner.createTable(new Table({
    name: 'classes_students_students',
    columns: [
        {
             name: 'classesId',
             type: 'uuid',
             isPrimary: true,
        },
        {
             name: 'studentsId',
             type: 'uuid',
             isPrimary: true,
        },
    ],
    foreignKeys: [
        {
            columnNames: ['classesId'],
            referencedColumnNames: ['id'],
            referencedTableName: 'classes',
        },
        {
            columnNames: ['studentsId'],
            referencedColumnNames: ['id'],
            referencedTableName: 'students',
        },
    ],
}))

Nomenclatures

Tables

Relationship table needs to follow the following formula nomeDaTabelaOriginal_nomeDoCampoManyToManyDaEntity_nomeDaOutraTabela

Campos

The fields that will relate the tables is simpler: nameTableId

Browser other questions tagged

You are not signed in. Login or sign up in order to post.