My database has a one to many relationship. When I perform a select operation, everything works correctly. However, when trying to insert data, the insertion occurs in the main table, but updates are triggered in other tables.
Error Log from Console
[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
Expected Behavior
I expect the insert operation on tblCategory to work correctly. The problem lies with tblBook where an update is being triggered instead of an insert.
View 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;
}