【问题标题】:One to many relationship does not insert parent一对多关系不插入父级
【发布时间】:2020-01-21 02:43:54
【问题描述】:

我有一对多的关系。当我选择时,选择可以正常工作,但是在尝试进行插入时,插入发生在主表中,但在其他表中发生更新。

控制台生成的日志

[0] query: BEGIN TRANSACTION

[0] query: INSERT INTO "tblCategory"("ID_CATEGORY", "NM_CATEGORY") VALUES (@0, @1)
-- PARAMETERS: [{"value":"BDA9A127-0851-4E2D-8FC7-52FBF27CFDF4","type":"uniqueidentifier","params":[]},{"value":Test,"type":"nvarchar","params":[]}]

[0] query: UPDATE "tblBook" SET "ID_CATEGORY" = @1 WHERE "ID_BOOK" = @0
-- PARAMETERS: ["F5465876-8003-44A6-BF97-9CBBE6D30C92",{"value":"BDA9A127-0851-4E2D-8FC7-52FBF27CFDF4","type":"uniqueidentifier","params":[]}]

[0] query: COMMIT

期待

对于表 tblCategory 正确生成插入,我需要表 tblBook 来生成插入,而不是正在发生的更新。

Code

author.entity.ts

@Entity('tblCategory')
export class Category {
  @PrimaryColumn({ name: 'ID_CATEGORY', type: 'uniqueidentifier' })
  id: string;

  @Column({ name: 'NM_CATEGORY', type: 'nvarchar' })
  name: string;

  @OneToMany(type => Book, book => book.category)
  @JoinTable({
    name: 'tblBook',
    joinColumn: { name: 'ID_BOOK' },
    inverseJoinColumn: { name: 'ID_CATEGORY' },
  })
  books: Book[];

}

category.service.ts

@Injectable()
export class ForragemPastoService {
  constructor(
    @InjectRepository(Category)
    private readonly repository: Repository<Category>,
  ) {}

  async save(category: Category): Promise<Category> {
    await this.repository.save(category);
    const data = await this.repository.findOne(category.id, {
      relations: ['books'],
    });
    return data;
  }
}

book.entity.ts

@Entity('tblBook')
export class Book {
  @PrimaryColumn({ name: 'ID_BOOK', type: 'uniqueidentifier' })
  id: string;

  @Column({ name: 'DS_TITLE', type: 'nvarchar' })
  title: string;

  @Column({ name: 'DS_SUBTITILE', type: 'nvarchar' })
  subtitle: string;

  @ManyToOne(() => Category, m => m.books)
  @JoinColumn({ name: 'ID_CATEGORY' })
  category: Category;
}

【问题讨论】:

  • 您好 Vinícius,欢迎来到 Stackoverflow! :-) 请编辑您的问题并从您的 gist 链接添加代码。该链接可能有一天会过期,因此在您的主题中包含所有必要信息非常重要。此外,请尝试更清楚地说明您的期望是什么以及实际发生的事情。见stackoverflow.com/help/how-to-ask

标签: typescript nestjs typeorm


【解决方案1】:

您是否尝试过设置级联?它可能会有所帮助:

@OneToMany(type => Book, book => book.category, {cascade: true})

【讨论】:

    猜你喜欢
    • 2017-02-12
    • 1970-01-01
    • 1970-01-01
    • 2021-06-30
    • 2015-03-16
    • 2022-12-18
    • 2018-03-28
    • 2019-04-17
    • 2021-03-09
    相关资源
    最近更新 更多