'TypeORM bulk insert?

How do i bulk insert multiple records in 1 query so my db will be efficient I want to create Office and insert multiple new equipments into that office. Table/model code:

OFFICE

@Entity({ name: 'offices' })
export class Office extends Timestamps {

    @OneToMany(() => Equipment, (equipment: Equipment) => equipment.office, {
        onDelete: 'CASCADE',
        onUpdate: 'CASCADE'
    })
    equipment: Array<Equipment>;
}

EQUIPMENT

@Entity({ name: 'equipment' })
export class Equipment extends Timestamps {
    @Column({
        name: 'equipment_id',
        type: 'int',
        nullable: false,
        width: 2,
        default: 0
    })
    equipment_id: number;

    @ManyToOne(() => Office, (office: Office) => office.equipment)
    @JoinColumn({ name: 'office_id' })
    office: Office;
}



Solution 1:[1]

I suggest you to use cascades property in relationships:

@Entity({ name: 'offices' })
export class Office extends Timestamps {

    @OneToMany(() => Equipment, (equipment: Equipment) => equipment.office, {
        cascade: true, // <= here
        onDelete: 'CASCADE',
        onUpdate: 'CASCADE'
    })
    equipment: Array<Equipment>;
}

Now if you set equipment when creating an instance of Office, it automatically insert an Equipment instance into database:

await Office.create({equipment: ['whatever']}).save();

Or if you use data mapper approach with repositories based on this link:

const officeRepository = connection.getRepository(Office);
const office = new Office();
const equipment1 = new Equipment(); // and set your properties or make more instances

office.equipment = [equipment1]; // or more instances
await officeRepository.save(office);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1