【问题标题】:How can I add entity to relation only with ID without fetching it?如何仅使用 ID 将实体添加到关系而不获取它?
【发布时间】:2020-02-18 07:24:31
【问题描述】:

我正在创建多对多关系

@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);

我知道这是错误的。

我该怎么做?

谢谢

【问题讨论】:

    标签: node.js typescript express typeorm


    【解决方案1】:

    我也有这个问题,我费了一番功夫,但我在 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]);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-05-11
      • 1970-01-01
      • 2018-02-16
      • 1970-01-01
      • 1970-01-01
      • 2016-07-12
      • 1970-01-01
      相关资源
      最近更新 更多