【问题标题】:Update many to many custom property of a table with TypeORM使用 TypeORM 更新表的多对多自定义属性
【发布时间】:2021-05-13 20:25:39
【问题描述】:

我正在使用 Nest Js 和 TypeOrm 构建应用程序。我在 ShoppingList 和 Item 之间有多对多的关系,如下所示:

购物清单

@Entity()
export class ShoppingList {
  @PrimaryGeneratedColumn('uuid')
  id: number;

  @Column()
  name: string;

  @CreateDateColumn({ name: 'created_At' })
  createdAt: Date;

  @Column({ default: 'open' })
  status: 'completed' | 'cancelled' | 'open';

  @ManyToOne(() => User, (User) => User.shopping_lists)
  owner: User;

  @OneToMany(
    () => ShoppingListItem,
    (shoppingListItem) => shoppingListItem.shoppingList,
  )
  items: ShoppingListItem[];
}

购物清单项目:

@Entity()
export class ShoppingListItem {
  @Column()
  quantity: number;

  @Column()
  checked: boolean;

  @ManyToOne(() => Item, (item) => item.lists, { primary: true })
  item: Item;

  @ManyToOne(() => ShoppingList, (shoppingList) => shoppingList.items, {
    primary: true,
  })
  shoppingList: ShoppingList;
}

项目:

@Entity()
export class Item {
  @PrimaryGeneratedColumn('uuid')
  id: number;

  @Column({ unique: true })
  name: string;

  @OneToMany(
    () => ShoppingListItem,
    (shoppingListItem: ShoppingListItem) => shoppingListItem.item,
  )
  lists: ShoppingListItem[];

  @ManyToOne(() => Category, (category) => category.items)
  category: Category;
}

我的意思是:如何更新多对多关系中的“已检查”自定义属性??

【问题讨论】:

    标签: javascript nestjs typeorm


    【解决方案1】:

    如果我理解,您可以将其更新为普通实体列

    this.ShoppingListItemRepository.update(id, {checked: true});
    

    您可以在 ShoppingList 服务中使用它来更改购物,并使用 {where to find related items}:

    购物清单服务:

    async updateShoppingList(ShoppingListID: number) {
    /...
        const results = await this.ShoppingListItemRepository.find({where:{
            shoppingList : ShoppingListID,
          }});
        const ids = results.map((item)=> item.id);
        await this.ShoppingListItemRepository.update(ids, {checked: true});
    

    【讨论】:

    • ShoppingListItemRepository 没有 id,因为它是一个多对多关系表,我应该放一个 id 吗?
    • 是的,把id,id对每个实体都有用
    猜你喜欢
    • 2020-10-09
    • 2021-02-08
    • 2021-12-26
    • 1970-01-01
    • 1970-01-01
    • 2022-01-08
    • 2012-11-27
    • 1970-01-01
    • 2020-11-14
    相关资源
    最近更新 更多