问题描述
我有两个实体-财产和所有者.一个财产可以有很多所有者,而所有者可以有很多财产.对于联接,请使用property_owner表.如何使用NestJS/TypeORM更新这种多对多关系?
I have two entities - Property and Owner. One Property can have a lot of Owners and Owner can have a lot of Properties. For join use property_owner table. How to update this many-to-many relation using NestJS/TypeORM?
@Entity('property')
export class Property extends EntityModel {
@Column({ length: 255, nullable: false })
name: string;
@ManyToMany(type => Owner, { cascade: true })
@JoinTable({
name: 'property_owner',
joinColumn: { name: 'propertyId', referencedColumnName: 'id'},
inverseJoinColumn: { name: 'ownerId', referencedColumnName: 'id'},
})
owners: Owner[];
}
@Entity('owner')
export class Owner extends EntityModel {
@Column({ length: 255, nullable: false })
name: string;
@ManyToMany(type => Property, { cascade: true })
@JoinTable({
name: 'property_owner',
joinColumn: { name: 'ownerId', referencedColumnName: 'id'},
inverseJoinColumn: { name: 'propertyId', referencedColumnName: 'id'},
})
properties: Property[];
}
以下用于保存和更新服务的方法:
Below my service's methods for save and update:
public create(req: Request): Promise<Dto> {
const dto: CreateDto = {
...req.body,
owners: this.formatJoinData(req.body.owners) //[1,2,3] => [{id:1},{id:2},{id:3}]
};
const entity = Object.assign(new Entity(), dto);
return this.repo.save(entity);
}
public update(req: Request): Promise<UpdateResult> {
const dto: EditDto = {
...req.body,
owners: this.formatJoinData(req.body.owners) //[1,2,3] => [{id:1},{id:2},{id:3}]
};
const id = req.params.id;
const entity = Object.assign(new Entity(), dto);
return this.repo.update(id, entity);
}
保存新媒体资源效果很好,但是当我尝试更新媒体资源时出现错误
Saving new Property work fine, but when I try update property I get error
[ExceptionsHandler] column "propertyId" of relation "property" does not exist
在两种情况下,所有者数据都看起来像[{id:1},{id:2},{id:3}].我认为保存/更新方法结果存在问题.保存方法返回给我们具有ID的实体,更新方法返回给我们不包含实体ID的UpdateResult.但是也许我们可以在某个地方变换/另外定义该值...
Owners data in both cases looks like [{id:1},{id:2},{id:3}]. I think problem in save/update methods results. Save method return to us Entity with id and update method return to us UpdateResult which not contain Entity id. But may be we can transform/additionally define this value somewhere...
推荐答案
我找到了解决方案.需要调用保存方法而不是更新.就我而言,更新将类似于
I found solution. Need to call save method instead update.In my case update will be looks like
import {plainToClass} from 'class-transformer';
public async update(req: Request): Promise<Dto> {
const found = await this.repo.findOneOrFail(req.params.id, {
relations: ['owners', 'electricMeter'],
});
const dto = {
...found,
...req.body,
owners: this.formatJoinData(req.body.owners) //[1,2,3] => [{id:1},{id:2},{id:3}]
updatedBy: this.getUser(req),
updatedDate: Date.now(),
};
return this.repo.save(plainToClass(Entity, dto));
}
此代码可以改进,但认为主要思想很清楚.
This code can be improved, but think that main idea is clear.
这篇关于NestJs使用连接表更新多对多关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!