typeorm迁移对联结表的两列都应用了ondelete:restrict

时间:2019-12-06 06:56:44

标签: typeorm

我在两个表-companiescategories之间有多对多关系。如果要关联任何公司,我想限制类别的删除。但反之亦然,即可以正常删除公司。

但是,迁移会从双方产生onDelete restrict的查询。

Company.entity.ts

@Entity('companies')
@Unique('unique_company_name', ['name'])
export class Company {
  @PrimaryGeneratedColumn({ type: 'int' })
  id: number;

  @Column({ type: 'varchar', length: 100 })
  name: string;

  //---- here ----

  @RelationId((company: Company) => company.categories)
  categoryIds: number[];

  @ManyToMany(() => Category, category => category.companies, {
    onDelete: 'RESTRICT',
    onUpdate: 'CASCADE',
  })
  @JoinTable({ name: 'company_category_mapping' })
  categories: Category[];

  //--------


  @RelationId((company: Company) => company.subCategories)
  subCategoryIds: number[];

  @ManyToMany(() => SubCategory, subCat => subCat.companies, {
    onDelete: 'RESTRICT',
    onUpdate: 'CASCADE',
  })
  @JoinTable({ name: 'company_sub_category_mapping' })
  subCategories: Category[];

}

Category.entity.ts

@Entity('categories')
@Unique('unique_category_name', ['name'])
export class Category {
  @PrimaryGeneratedColumn()
  id: number;
  @Column({ type: 'varchar', length: 100 })
  name: string;

  //-------- here --------
  @ManyToMany(() => Company, company => company.categories,{
    onDelete:"CASCADE",
    onUpdate:"NO ACTION"
  })
  companies: Company[];

  @RelationId((category: Category) => category.companies)
  company_ids: number[];
  //---------------

  @OneToMany(() => SubCategory, subCat => subCat.category)
  subCategories: SubCategory[];

}

因此,如上面的代码所示,我在公司实体中设置了onDelete:'RESTRICT',以限制类别的删除,并在类别实体中设置了onDelete:'CASCADE',以使公司的删除不受限制。

但是当我运行migrations:generate(npm命令)时,它会从两侧以onDelete restrict的形式生成sql-

 await queryRunner.query(
      'ALTER TABLE `company_category_mapping` ADD CONSTRAINT `FK_70d2905e6753d403b800a12ee9f` FOREIGN KEY (`categories_id`) REFERENCES `categories`(`id`) ON DELETE RESTRICT ON UPDATE NO ACTION',
      undefined,
    ); // as expected ✔
    await queryRunner.query(
      'ALTER TABLE `company_category_mapping` ADD CONSTRAINT `FK_c210fdf34a6fd64bf7070d421b1` FOREIGN KEY (`companies_id`) REFERENCES `companies`(`id`) ON DELETE RESTRICT ON UPDATE NO ACTION',
      undefined,
    );// (✖) should be `CASCADE`

那么,这是迁移的错误吗?还是我缺少什么?

0 个答案:

没有答案