NestJS TypeORM发布具有多个直通类型关系的请求



我正试图用一个自定义字段实现一个多对多关系,就像下面所示的那样。我的数据与他给出的例子不同,但关系的结构是相同的。我能够成功地创建关系,但我遇到了一个问题,即产品的外键(product_id(为null,即使客户端正在发送该字段的数据。由于某种原因,TypeORM正在删除它并输入一个空值。

以下是连接表的结构:

@Entity()
export class ShipmentProduct {
@PrimaryGeneratedColumn()
id: number;
@Column()
qty: number;
@Column()
pick_up: boolean;
@ManyToOne(type => Shipment, shipment => shipment.shipmentProducts)
@JoinColumn({ name: 'shipment_id' })
shipment: Shipment;
@ManyToOne(type => Product, product => product.shipmentProducts)
@JoinColumn({ name: 'product_id' })
product: Product;
}

我的服务通过以下功能提交数据:

async create(shipmentData: CreateShipmentDto): Promise<Shipment> {
const shipment = new Shipment();
shipment.bill_of_lading = shipmentData.bill_of_lading;
shipment.trailer_number = shipmentData.trailer_number;
shipment.ship_date = shipmentData.ship_date;
shipment.delivery_date = shipmentData.delivery_date;
shipment.carrier = shipmentData.carrier;
shipment.release_code = shipmentData.release_code;
shipment.payment_date = shipmentData.payment_date;
shipment.comments = shipmentData.comments;
shipment.client = await this.clientsRepository.findOne(shipmentData.client_id);
shipment.shipmentProducts = shipmentData.shipmentProducts;
return await this.shipmentsRepository.save(shipment);
}

提交表单时,装运数据会与shipmentProducts一起成功保存,但是product_id会被删除,即使shipmentData包含product_id的值。

这是发货数据的控制台日志

{
client_id: 1,
bill_of_lading: '12',
trailer_number: '21',
ship_date: '2020-04-02T04:00:00.000Z',
delivery_date: '',
carrier: '21',
release_code: '21',
fuel_surcharge: '21',
payment_date: '',
comments: '',
shipmentProducts: [
{ product_id: 1966, qty: '12', pick_up: false },
{ product_id: 1966, qty: '12', pick_up: false }
]
}

但是,shipmentProducts的insert语句省略了product_id,并坚持使用默认值。为什么?我该如何修复它?

INSERT INTO `shipment_product`(`id`, `qty`, `pick_up`, `shipment_id`, `product_id`) VALUES (DEFAULT, ?, ?, ?, DEFAULT) -- PARAMETERS: ["12",0,10]

事实证明,我需要在发布请求中至少发送一个部分product对象,而不仅仅是product_id。所以这似乎奏效了。问题出在客户端,而不是NestJS或TypeORM。

shipmentProducts: [
{ product: { id:1966 }, qty: 12, pick_up: false }
{ product: { id:1845 }, qty: 20, pick_up: false }
]

这是一个非常常见的问题。

有用的解决方法是使用:

@Entity()
export class ShipmentProduct {
@PrimaryGeneratedColumn()
id: number;
@ManyToOne(type => Product, product => product.shipmentProducts)
@JoinColumn({ name: 'product_id' })
product: Product;
@Column({name: 'product_id'})
productId: Product['id'];
}

所以你可以直接通过productId

最新更新