【问题标题】:How can i create or update one entity on another was created如何在另一个实体上创建或更新一个实体已创建
【发布时间】:2021-07-05 04:35:57
【问题描述】:

感谢您的帮助

我的数据库中有几个表:商店、销售和库存,我想在我的销售表中保存新销售时更新库存。

有我的实体 出售

@Entity()
export class Sale {
  @PrimaryGeneratedColumn()
  id: number

  @ManyToOne((type) => Store, (store) => store.sales)
  store: Store

  @Column()
  productId: number

  @Column()
  user: number

  @Column()
  count: number

  @Column()
  sum: number

  @CreateDateColumn()
  createDate: Date
}

库存

@Entity()
export class Stock {
  @PrimaryGeneratedColumn()
  id: number

  @Column()
  product: number

  @ManyToOne((type) => Store, (store) => store.stocks)
  store: Store

  @Column()
  count: number
}

stock 实体包含产品 id 和商店 id, 销售实体也包含这些属性。我想要的是? 好吧,当我保存在 db new sale 中时,我想在 stock 表中找到 stock.product = sale.product 和 stock.store = sale.store 的项目,然后像 stock.count = 一样更新它的计数字段stock.count + 销售计数。这可能吗?

我可以在销售服务中使用库存服务并实现这个逻辑,但我认为会有一个非常干净的方法......

【问题讨论】:

    标签: javascript mysql typescript nestjs typeorm


    【解决方案1】:

    每次对销售实体执行操作时,都使用级联在两侧保存、更新和删除 注意 => 级联仅在一侧工作 => 销售方

    @Entity()
    export class Sale {
      @PrimaryGeneratedColumn()
      id: number
    
      @ManyToOne((type) => Store, (store) => store.sales , {cascade : true})
      store: Store
    
      @Column()
      productId: number
    
      @Column()
      user: number
    
      @Column()
      count: number
    
      @Column()
      sum: number
    
      @CreateDateColumn()
      createDate: Date
    }
    

    【讨论】:

      猜你喜欢
      • 2013-02-19
      • 1970-01-01
      • 1970-01-01
      • 2023-03-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-12
      • 1970-01-01
      相关资源
      最近更新 更多