TypeORM保存嵌套对象 [英] TypeORM save nested objects

查看:19
本文介绍了TypeORM保存嵌套对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个Express(使用TypeORM)+ReactJS应用。

问题是我有3个实体通过OneToMany关系链接,如下所示:

  1. 客户
  2. 产品(链接到客户)
  3. 型号(链接到产品)
import { Product } from './product.entity'

@Entity('customer')
export class Customer extends BaseEntity{
    @PrimaryGeneratedColumn()
    readonly id: number;
   
    @Column ({name: 'name'})
    name : string;

    @Column ({name: 'test', nullable: true})
    test : string;

    @OneToMany(() => Product, product => product.customer)
    // @JoinColumn({ name: 'product_id' })
    products: Product[]
}
import {Customer} from './customer.entity'
import {Model} from './model.entity'

@Entity('product')
export class Product extends BaseEntity{
    @PrimaryGeneratedColumn()
    readonly id: number;
   
    @Column ({name: 'name'})
    name : string;

    @Column ({name: 'test', nullable: true})
    test : string;

    @Column ({name: 'deleted', nullable: true})
    deleted : string;
    
    @ManyToOne(() => Customer, customer => customer.products)
    @JoinColumn({ name: 'customer_id' })
    customer: Customer;

    @OneToMany(() => Model, model => model.product)
    @JoinColumn({ name: 'customer_id' })
    models: Model[]
}
import { Product } from "./product.entity";

@Entity('model')
export class Model extends BaseEntity{
    @PrimaryGeneratedColumn()
    readonly id: number;
   
    @Column ({name: 'name'})
    name : string;

    @Column ({name: 'size', nullable: true})
    size : string;

    @Column ({name: 'deleted', nullable: true})
    deleted : string;
    
    @ManyToOne(() => Product, product => product.models)
    @JoinColumn({ name: 'product_id' })
    product: Product;
}

Express中的保存方法为:

  static add = async(req: Request, res)=> {
    const connection = getConnection();
    const queryRunner = connection.createQueryRunner();
    await queryRunner.connect();
    await queryRunner.startTransaction();
    try {
      let customer: Customer
      customer = await queryRunner.manager.getRepository(Customer).findOneOrFail(req.body.id)

      const productsReq: Array<Product> = req.body.products
      productsReq.forEach(async (product: any) => {
        let updatedProd =  {...product, customer: customer}
        const savedProd = await queryRunner.manager.getRepository(Product).save({...updatedProd})
        product.models.forEach(async (model: any) => {
          let updatedModel = {...model, product: savedProd}
          await queryRunner.manager.getRepository(Model).save(updatedModel)
        });
      });

      await queryRunner.commitTransaction();
      return res.send('Saving done')

    } catch (error) {
      console.log(error)
      await queryRunner.rollbackTransaction();
      res.status(500).send('Some error occurs');
    } finally {
    }
  }

目前,在数据库中,我有以下数据:

1个ID为30的客户

名称 id 测试
第一个客户 30 测试栏

1个ID为119的产品链接到客户30

id 名称 测试 Customer_id 已删除
119 第一款产品 测试栏 30

2个型号,ID:90和91,链接到产品119

id 名称 大小 已删除 product_id
91 没有ID的第二个型号 2000 119
90 ID为的第一个型号 1000 119
接下来,在Reaction中,我尝试只更新id为90的模型,并添加一个新模型。 (因此我不会将所有型号发送到后端,ID为91的型号不会发送)。

从前端发送到后端的JSON对象如下:

{
    "id": 30,
    "name": "first customer",
    "test": "test column",
    "products": [
        {
            "id" : 119,   
            "name": "first product",
            "test": "test column",
            "models": [
                {
                    "id": 90,
                    "name": "first model with id",
                    "size": 1000
                },
                {
                    "name": "second model witout id",
                    "size": 2000
                }
            ]
        }

    ]
}

但问题出在数据库中,对于ID为91的模型,表&Quot;Model&Quot;上的前向键";设置为NULL,并插入新行(92)。

结果为:

|id|name|size|deleted|product_id|
|--|----|----|-------|----------|
|91|second model witout id|2000|||
|90|first model with id|1000||119|
|92|second model witout id|2000||119|

如何在不发送数据库中所有现有模型的情况下添加新模型并更新现有模型?

推荐答案

我想我找到了解决方案。

我更改了Express的保存方法,如下所示:

  static add = async(req: Request, res)=> {
    const connection = getConnection();
    const queryRunner = connection.createQueryRunner();
    await queryRunner.connect();
    await queryRunner.startTransaction();
    try {
      let customer: Customer
      let customerReq: any = req.body
      customer = await queryRunner.manager.getRepository(Customer).findOneOrFail(req.body.id)
      const productsReq: Array<Product> = req.body.products
      
      productsReq.forEach(async (product: any) => {
        let updatedProd =  {...product, customer: customer}
        let addedModels: Model[] = []
        product.models.forEach(async (model: any) => {
          const updatedModel = await queryRunner.manager.getRepository(Model).save({...model, product: product})
          addedModels.push(updatedModel)
        });
        const existingProd = await queryRunner.manager.getRepository(Product).save({...updatedProd})
        await (await existingProd.models).push(...addedModels)
        const savedProd = await queryRunner.manager.getRepository(Product).save({...updatedProd})
      });

      await queryRunner.commitTransaction();
      return res.send('Adding ok')

    } catch (error) {
      console.log(error)
      await queryRunner.rollbackTransaction();
      res.status(500).send('Something went terribly wrong');
    } finally {
      console.log('release')
      // await queryRunner.release();
    }
  }

奇怪,因为启动了2个事务:

query: START TRANSACTION
query: SELECT "Customer"."id" AS "Customer_id", "Customer"."name" AS "Customer_name", "Customer"."test" AS "Customer_test" FROM "customer" "Customer" WHERE "Customer"."id" IN ($1) -- PARAMETERS: [30]
query: SELECT "Customer"."id" AS "Customer_id", "Customer"."name" AS "Customer_name", "Customer"."test" AS "Customer_test" FROM "customer" "Customer" WHERE "Customer"."id" IN ($1) -- PARAMETERS: [30]
query: COMMIT
query: SELECT "Model"."id" AS "Model_id", "Model"."name" AS "Model_name", "Model"."size" AS "Model_size", "Model"."deleted" AS "Model_deleted", "Model"."product_id" AS "Model_product_id" FROM "model" "Model" WHERE "Model"."id" IN ($1) -- PARAMETERS: [132]
query: SELECT "Product"."id" AS "Product_id", "Product"."name" AS "Product_name", "Product"."test" AS "Product_test", "Product"."deleted" AS "Product_deleted", "Product"."customer_id" AS "Product_customer_id" FROM "product" "Product" WHERE "Product"."id" IN ($1) -- PARAMETERS: [119]
query: INSERT INTO "model"("name", "size", "deleted", "product_id") VALUES ($1, $2, DEFAULT, $3) RETURNING "id" -- PARAMETERS: ["second model witout id",2000,119]
release

 Morgan -->  POST 200 /test @ Tue, 04 May 2021 14:28:08 GMT ::ffff:127.0.0.1 from undefined PostmanRuntime/7.28.0

query: START TRANSACTION
query: SELECT "Product"."id" AS "Product_id", "Product"."name" AS "Product_name", "Product"."test" AS "Product_test", "Product"."deleted" AS "Product_deleted", "Product"."customer_id" AS "Product_customer_id" FROM "product" "Product" WHERE "Product"."id" IN ($1) -- PARAMETERS: [119]
query: UPDATE "model" SET "size" = $2 WHERE "id" IN ($1) -- PARAMETERS: [132,8000]
query: COMMIT

这篇关于TypeORM保存嵌套对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆