Form a one-to-many relationship from a collection of elements

Seeking assistance with a programming issue I've been grappling with. Despite extensive research online, I haven't been able to find a solution. As someone new to coding, I would greatly appreciate guidance.

The specific task at hand involves establishing a 1-n relationship. The "1" corresponds to the Business entity, whereas the "n" pertains to data extracted from an array of objects.

My objectives are as follows:

  1. Set up the Business entity
  2. Create Trading Entities and associate them with the Business. Each Trading Entity's name should be derived from BN_NAME, while its status should originate from BN_STATUS.

While I am currently utilizing NestJS, any support in TypeScript would be invaluable for my learning process.

Thank you in advance for your help.

-Paul

Below is the schema I am working with:

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
}

Here is the 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
  }
]

Answer №1

Utilizing an array of objects, you have the ability to simultaneously generate both `Business` and `TradingEntity` records through a single Prisma query by employing the `connectOrCreate API`.

Below is a solution to integrate the data from the array of objects into your database.

// If we assume that this code is being executed within an async function
// And if the array of objects is being stored in a variable named "businessData"

for (const data of businessData) {
    const tradingEntity = await prisma.tradingEntity.create({
        data: {
            Name: data.BN_NAME,
            Status: data.BN_STATUS,
            Business: {
                connectOrCreate: {
                    /*
                    * This will either connect to an existing "Business" record with a matching BN_ABN if it exists,
                    * OR
                    * It 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)
                    }
                }
            }
        }
    });
}
   

Based on the provided array of objects, the above code segment will:

  1. Create two `TradingEntity` records with names "Synergy Evolved" and "VALUERACK".
  2. Create one `Business` record with a BN_ABN of 922083948.

You may also want to consider modifying the field names in `TradingEntity` from PascalCase to camelCase as recommended by the naming conventions suggested in the Prisma documentation.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Could a tslint rule be implemented in Typescript classes to ensure method return types are enforced?

After diving into the tslint rules here, it seems that although the typedef rule's call-signature option might be close to what I need, it doesn't address the absence of a return type. Is there a specific rule (if one exists) that can enforce re ...

Angular 2 - Dragula for ng2

<div *ngFor="let col of columns"> ... <div [dragula]="'tickets-list'" [dragulaModel]="col.tickets" (drop)="onDrop($event, col)"> <ul> <li *ngFor="let ticket of col.tickets"> {{ ticket }} </li ...

Show the interface value for an array type

I have created a component to display API data. The structure of the component is as follows: HTML: <div *ngFor="let customer of customers"> <p>Name: {{customer?.name}}</p <p>Phone: {{customer?.phoneNumbers}}</p </div&g ...

What is the best way to display API error messages to the user?

When a user tries to upload a file that is not an image, I need to display the error message returned from a REST API. The JSON response received from the API will look something like this: { "publicError": "Could not be uploaded, it is not an image! ...

Unable to show the input's value

Need help in taking user input to display calculated values //html <div class="empty"> <h5> Enter Empty Seats </h5> <ion-item> <ion-input placeholder="Enter Number of Empties.." type="number" name="emptySeats" [( ...

What is the best way to incorporate ControlContainer in an Angular component's unit test?

Is there a way to include ControlContainer in an Angular unit test? The error message I am encountering reads: NullInjectorError: StaticInjectorError(DynamicTestModule)[ChildFormComponent -> ControlContainer]: StaticInjectorError(Platform: core) ...

Generate interfaces with typescript axios generator only using OpenApi Generator

Recently, I've been utilizing the OpenApi Generator for TypeScript alongside Axios, and I must say it's been functioning really well! However, one thing that has crossed my mind is how to generate classes instead of interfaces. For instance, whe ...

Using *ngFor to iterate through elements with distinct styles

Is there a way to assign different classes to buttons generated using *ngFor without changing the class for all previously created buttons when toggled? I have 2 search bars adding text to the same array, displayed as buttons. I want to differentiate betwe ...

Having trouble with enzyme in React Typescript application

One of my components is called app.tsx import React, { useState } from "react"; const TestComponent = () => { return( <> <div className="head">hey there</div> <select name="xyz" id=&qu ...

Exploring the possibility of integrating direct search functionality into the URL bar within an Angular application

One interesting feature I observed on GitHub is that after typing "github.com" in the URL bar, you can directly search by pressing the spacebar, which activates the "search mode." Here's how it looks like on Chrome: https://i.sstatic.net/XIgJu.png I ...

"Type 'Unknown' cannot be assigned to the specified type: Typescript Error encountered while using

I encountered an error message in my Redux Observable setup. Any advice on how to resolve this issue? The error states: 'Argument of type 'OperatorFunction<ITodo[], Action<{ params: { url: string; }; } & { result: { todos: ITodo[]; }; ...

Changing routes in Angular causes the @input value to update

Working with Angular 8, I have a setup with two components: the parent component and the child component. The parent component needs to pass an object or string when the URL parameters change. In the parent component, I implemented this code snippet that ...

Error: It appears that the callback with the specified ID for the module <unknown> cannot be found

I decided to create a yarn package that includes common components, services, utils, and more for my project. After creating the package, I added an index.ts file in the src folder to export all components. Once the package was built and added to my projec ...

Publishing Typescript to NPM without including any JavaScript files

I want to publish my *.ts file on NPM, but it only contains type and interface definitions. There are no exported JavaScript functions or objects. Should I delete the "main": "index.js" entry in package.json and replace it with "main": "dist/types.ts" inst ...

Using React with Typescript and Redux Toolkit may result in an error where you cannot use a string to index type 'Writable Draft'

Greetings, I'm encountering an issue where I receive the error message mentioned in the title - "expression of type string can't be used to index type 'WritableDraft'." I aim to implement a dynamic solution to eliminate the need for mul ...

Within an Angular test scenario, execute a static method from a service that triggers an HTTP get request to fetch stored JSON data. This data is then retrieved and returned back to the service

Currently, I am facing a challenge in my Angular test case where I am trying to load JSON data via an HTTP call. The issue arises when a static method is called from a service spec file named "url-service.spec" to another service named "load-json.service. ...

TypeScript Tutorial: How to retrieve the data type of a deeply nested object

I have a question about extracting the type of a nested object with similar structures. The object in question contains multiple sub-objects that all follow the same pattern. const VALUES = { currentStreak: { display: "Current streak", ...

Tips for enabling Azure Blob Storage file uploads in a React app while staying compliant with Content Security Policies

I am using an Azure Storage Account and a container to upload files from my React application. Through an Azure Function, I receive SAS Keys with the necessary permissions for file uploading. My CORS settings in the storage account allow all connections. ...

Encountering a MongooseServerSelectionError: connection failure to 127.0.0.1:27017 while trying to connect to MongoDB

I am currently working on a basic node.js TypeScript API with MongoDB integration, and I am utilizing Docker to containerize the application. Below is a snippet from my index.ts file: import express from 'express'; import app from './app&ap ...

Changing the request body type in Express from any to unknown to allow for greater flexibility

Currently, I'm delving into the world of ambient modules and declaration-merging as I attempt to customize the Express TypeScript definition file for Request. I have managed to add extra properties, but I am struggling to override the existing ones. ...