从对象数组创建 1-n

Create a 1-n from an array of objects

我想知道是否有人可以帮助我解决这个问题。我花了一段时间在网上搜索但找不到任何东西。我只是在学习编程,我卡住了。

我正在尝试创建 1-n 关系。 1 是业务,n 来自对象数组中的数据。

我愿意:

  1. 创建业务
  2. 创建贸易实体并将它们 link 交给企业。 TradingEntity.name 来自 BN_NAME,TradingEntity.Status 来自 BN_STATUS

我正在使用 NestJS,但在 typescript 中的任何帮助都会很棒,因为我会尝试从中学习。

感谢您的帮助。

-保罗

我的架构是:

model Business {
  id                Int                          @id @default(autoincrement())
  BN_ABN            Int?                         @unique
  tradingEntities   TradingEntity[]
}

model TradingEntity {
  id                Int            @id @default(autoincrement())
  Business          Business       @relation(fields: [BusinessId], references: [id])
  BusinessId        Int
  Name              String         //  BN_NAME from array of objects 
  Status            String         //  BN_STATUS from array of objects
}

这是对象数组。

[
  {
    _id: 1812602,
    REGISTER_NAME: 'BUSINESS NAMES',
    BN_NAME: 'Synergy Evolved',
    BN_STATUS: 'Registered',
    BN_REG_DT: '08/09/2012',
    BN_CANCEL_DT: null,
    BN_RENEW_DT: '08/09/2021',
    BN_STATE_NUM: null,
    BN_STATE_OF_REG: null,
    BN_ABN: '48166724204',
    rank: 0.0573088
  },
  {
    _id: 2199676,
    REGISTER_NAME: 'BUSINESS NAMES',
    BN_NAME: 'VALUERACK',
    BN_STATUS: 'Registered',
    BN_REG_DT: '11/04/2012',
    BN_CANCEL_DT: null,
    BN_RENEW_DT: '11/04/2015',
    BN_STATE_NUM: 'B2460084Y',
    BN_STATE_OF_REG: 'VIC',
    BN_ABN: '48166724204',
    rank: 0.0573088
  }
]

您可以使用对象数组通过单个 Prisma 查询创建 BusinessTradingEntity 记录。为此,您需要使用 connecOrCreate API.

这是将对象数组中的数据插入数据库的解决方案。

// Assuming executing inside an async function
// Assuming array of objects is stored in a variable called "businessData"

for (const data of businessData) {
    const tradingEntity = await prisma.tradingEntity.create({
        data: {
            Name: data.BN_NAME,
            Status: data.BN_STATUS,
            Business: {
                connectOrCreate: {
                    /*
                    * Will connect to an existing "Business" record with matching BN_ABN if it exists,
                    * OR
                    * Will create a new "Business" record if there is no existing record with a matching BN_ABN.
                    */
                    where: {
                        BN_ABN: parseInt(data.BN_ABN)  //BN_ABN is a string in the object, so converted to Int to comply with Prisma Schema.
                    },
                    create: {
                        BN_ABN: parseInt(data.BN_ABN)
                    }
                }
            }
        }
    });
}
   

根据您提供的对象数组,上面的代码片段将

  1. 创建两个 TradingEntity 记录 names“Synergy Evolved”和“VALUERACK”。
  2. 创建一个 Business 记录 BN_ABN 为 922083948。

或者,您应该考虑将 TradingEntity 中的字段名称从 PascalCase 更改为 camelCase。这更符合 Prisma 文档中建议的 naming conventions