如何在不获取ID的情况下仅将实体添加到关系中?

时间:2019-06-26 20:26:29

标签: node.js typescript express typeorm

我正在建立多对多关系

@Entity({
    name: 'product'
})
export class Product {
    @PrimaryGeneratedColumn()
    id: number;

    @Column()
    name: string;

    @Column({type: 'decimal', precision: 13, scale: 2})
    price: number;

    @ManyToMany(() => Tag, (tag: Tag) => tag.products)
    @JoinTable({
        name: 'product_tag'
    })
    tags: Tag[];

    @CreateDateColumn()
    createdAt: Timestamp;

    @UpdateDateColumn()
    updatedAt: Timestamp;
}
@Entity({
    name: 'tag'
})
export class Tag {
    @PrimaryGeneratedColumn()
    id: number;

    @Column()
    name: string;

    @ManyToMany(() => Product, (product: Product) => product.tags)
    products: Product[];

    @CreateDateColumn()
    createdAt: Timestamp;

    @UpdateDateColumn()
    updatedAt: Timestamp;
}

说db中有一些标签。例如:Tag = [{id: 1, name: 'pc'}, {id: 2, name: 'laptop'}]

我有产品Product = [{id: 1, name: 'Zenbook', price: 10000 }]

现在我需要将那些标签添加到产品中。

我想做这样的事情

const product = await this.repository.findOne({id: 1});

product.tags = [{id: 1}, {id:2}];

await this.repository.save(product);

我知道这是错误的。

我该怎么做?

谢谢

1 个答案:

答案 0 :(得分:0)

我也有这个问题,花了一些时间,但我在TypeORM文档中发现了Working with Relations

根据您的情况

await getConnection()
    .createQueryBuilder()
    .relation(Product, "tags")
    .of(product)
    /**
     * Adds (binds) given value to entity relation.
     * Value can be entity, entity id or entity id map (if entity has composite ids).
     * Value also can be array of entities, array of entity ids or array of entity id maps (if entity has composite ids).
     * Works only for many-to-many and one-to-many relations.
     * For many-to-one and one-to-one use #set method instead.
     */
    .add([1, 2]);