I've got two tables services
and offers
. an Offer can have many services and a service can have many offers.
My service entity
@Entity('Services')
export class ServiceEntity extends BaseEntity {
@PrimaryGeneratedColumn()
serviceKey: number;
....
@ManyToMany(() => OffersEntity, (offer) => offer.services)
@JoinTable({
name: 'offersXservices',
inverseJoinColumn: {
name: 'offerKey',
referencedColumnName: 'offerKey'
},
joinColumn: {
name: 'serviceKey',
referencedColumnName: 'serviceKey',
},
})
offers?: OffersEntity[];
}
And My Offers entity is defined like this:
@Entity('Offers')
export class OffersEntity extends BaseEntity {
@PrimaryGeneratedColumn()
offerKey: number;
....
@ManyToMany(() => ServiceEntity, (service) => service.offers)
@JoinTable({
name: 'offersXservices',
inverseJoinColumn: {
name: 'serviceKey',
referencedColumnName: 'serviceKey'
},
joinColumn: {
name: 'offerKey',
referencedColumnName: 'offerKey',
},
})
services?: ServiceEntity[];
}
I'm getting an error when I tried to create an offer record with some services : query failed: INSERT INTO "offersXservices"("offerKey", "serviceKey") VALUES (DEFAULT, DEFAULT), (DEFAULT, DEFAULT) error: error: null value in column "offerKey" violates not-null constraint
.
I don't understand why this is happening? in the above generated query the DEFAULT
should be replaced with offerKey and serviceKey respectively. can anyone help me on that?
Here is the code which I use to insert into offer record.
const _offerEntity = await OffersEntity.create({
vendorKey: input.vendorKey,
name: input.name,
description: input.description,
startAt: input.startAt,
expiry: input.expiry,
services: await ServiceEntity.find({
where: {
serviceKey: In(input.services)
}
})
});
await queryRunner.manager.save(_offerEntity);
Any help would be appreciated :)
PS: Database is postgresql
I didn't find a proper solution to this question. I ended up using raw sql
queries with typeorm.
for (const _service of input.services) {
await queryRunner.manager.query(`INSERT INTO "offersXservices"("offerKey", "serviceKey") VALUES (${_offerEntity.offerKey}, ${_service})`);
}
Hope it helps someone.