Updating a Parent entity in Prisma with the option to also update its associated Child entity in a

I am currently managing a Parent Child (One-To-One) Relationship structured like this:

model Account {
  id Int @id @default(autoincrement())

  createdAt DateTime @default(now())
  updatedAt DateTime @updatedAt

  billingAddress Address?
  name           String

  @@map("Accounts")
}

model Address {
  id         Int      @id @default(autoincrement())
  city       String?
  country    String?
  postalCode Int?
  state      String?
  street     String?
  accountId  Int      @unique
  account    Account  @relation(fields: [accountId], references: [id])
}

I have a need to Update the Parent Record without having to update the Child Record simultaneously. Also, it would be beneficial if I could update both the Parent and Child Records at once. However, when attempting to only send data for updating the Parent Record, an Error is encountered.

Below are my DTOs utilized for Creating and Editing the Entities:

Create / Edit Account:

export class CreateAccountDto {

    @IsString()
    @IsOptional()
    name: string;

    @IsOptional()
    billingAddress?: CreateAddressDto;

}

Create / Edit Addresss:

export class EditAddressDto {

    @IsString()
    @IsOptional()
    city?: string;

    @IsString()
    @IsOptional()
    country?: string;

    @IsNumber()
    @IsOptional()
    postalCode?: number;

    @IsString()
    @IsOptional()
    state?: string;

    @IsString()
    @IsOptional()
    street?: string;

    @IsInt()
    @IsOptional()
    accountId: number;

}

The process of creating and editing the Account is as follows:

async editAccount(accountId: number, dto: EditAccountDto) {
    let account;

    console.log({dto})

    account = await this.prisma.account.update({
        where: {
            id: accountId
        },
        data: {
            ...dto,
            billingAddress: {
                update: {
                    ...dto.billingAddress
                }
            }
        },
        include: {
            billingAddress: true
        }
    });

    console.log(account)

    return account;
}

However, upon attempting to Edit the Account with specific Data provided, an Error is encountered:

{
    "name": "Test Account Create2",
    "billingAddress": {
        "id": 2,
        "city": "Dortmund",
        "state": "NRW",
        "postalCode": 44442,
        "country": "Germany",
        "street": "Benninghofer Heide 63",
        "accountId": 10000001
    }
}

The following Error is generated:

Unknown arg `accountId` in data.billingAddress.update.accountId for type AddressUncheckedUpdateWithoutAccountInput. Did you mean `country`? Available args:
type AddressUncheckedUpdateWithoutAccountInput {
  id?: Int | IntFieldUpdateOperationsInput
  city?: String | NullableStringFieldUpdateOperationsInput | Null
  country?: String | NullableStringFieldUpdateOperationsInput | Null
  latitude?: Decimal | NullableDecimalFieldUpdateOperationsInput | Null
  longitude?: Decimal | NullableDecimalFieldUpdateOperationsInput | Null
  postalCode?: Int | NullableIntFieldUpdateOperationsInput | Null
  state?: String | NullableStringFieldUpdateOperationsInput | Null
  street?: String | NullableStringFieldUpdateOperationsInput | Null
}


    at Document.validate (C:\Users\Simon\IdeaProjects\crm-tool\crm-backend\node_modules\@prisma\client\runtime\index.js:29297:20)
    at serializationFn (C:\Users\Simon\IdeaProjects\crm-tool\crm-backend\node_modules\@prisma\client\runtime\index.js:31876:19)
    at runInChildSpan (C:\Users\Simon\IdeaProjects\crm-tool\crm-backend\node_modules\@prisma\client\runtime\index.js:25100:12)
    at PrismaService._executeRequest (C:\Users\Simon\IdeaProjects\crm-tool\crm-backend\node_modules\@prisma\client\runtime\index.js:31883:31)
    at consumer (C:\Users\Simon\IdeaProjects\crm-tool\crm-backend\node_modules\@prisma\client\runtime\index.js:31810:23)
    at C:\Users\Simon\IdeaProjects\crm-tool\crm-backend\node_modules\@prisma\client\runtime\index.js:31815:51
    at AsyncResource.runInAsyncScope (node:async_hooks:199:9)
    at C:\Users\Simon\IdeaProjects\crm-tool\crm-backend\node_modules\@prisma\client\runtime\index.js:31815:29
    at runInChildSpan (C:\Users\Simon\IdeaProjects\crm-tool\crm-backend\node_modules\@prisma\client\runtime\index.js:25100:12)
    at PrismaService._request (C:\Users\Simon\IdeaProjects\crm-tool\crm-backend\node_modules\@prisma\client\runtime\index.js:31812:22)

Answer №1

According to the error message, attempting to update the address with a specified accountId is not permitted in this scenario. To resolve this issue, simply remove the accountId from your DTO and the problem should be resolved.

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

"Changing the name of a symbol that is automatically imported from an internal library in

Within my module, I find myself using the Element class that is implicitly imported from the "dom" internal library. However, I also need to create my custom Element class within the same module. This presents a problem due to the name collision and poten ...

Tips for importing a library in a TypeScript file that expands a JavaScript prototype

After following the instructions provided in this question, I am experimenting with integrating Moment.js to enhance the capabilities of the Date prototype within a TypeScript project. The process of extending the Date prototype appears successful, as out ...

How can CakePHP 3 perform a table join using a different table?

I have been working on creating a DB structure that involves the following entities: https://i.sstatic.net/GvVtq.gif My focus is on establishing the relationship between: sales_transaction products products_in_transaction My goal is to set up the rela ...

Modifying the appearance of a Component within a NavLink

I'm currently working on a navbar using NavLink from React-Router-Dom. It's fine to use the 'isActive' prop to style the active Link, but I'm stuck on how to style the subelements inside it. For more specific details, please take a ...

Angular - How to fix the issue of Async pipe not updating the View after AfterViewInit emits a new value

I have a straightforward component that contains a BehaviorSubject. Within my template, I utilize the async pipe to display the most recent value from the BehaviorSubject. When the value is emitted during the OnInit lifecycle hook, the view updates correc ...

I made some adjustments to the program, but I'm having trouble identifying the issue

Here's a simple form I'm using to input and send the category name: <form action="insertexp.php" method="post"> Category Name: <input type="text" name="name"><br> <input type="submit"> </form> This is my PHP script ...

What steps are necessary to integrate barrel file imports with my Angular 2 application?

Following the Angular 2 style guideline 04-10 Create and Import Barrels can be challenging, as it may lead to unexpected file loading issues. When running my app, I noticed that Angular attempts to load a non-existent file named "my-component-name-here.js" ...

steps to authenticate with dynamic database information instead of hard-coded data

After following a tutorial, I successfully created my first register login system in dot net and angular. The issue I encountered is that the author used static data in the tutorial's code example. However, I want to implement my own database data. As ...

"Exploring the wonders of asynchronous programming with NodeJS - join our class on utilizing

I attempted something I believed would be straightforward using: nodejs 8.6, MariaDB, MySQL2/promise and classes. However, it is not functioning as expected: Below is a simple example: const mysql = require('mysql2/promise'); class mySQLClass { ...

Angular 2 approach to retrieving items from an Observable<Xyz[]>

After reviewing the Typescript code in an Angular 2 service: getLanguages () { return this.http.get(this._languagesUrl) .map(res => <Language[]> res.json().data) .catch(this.handleError); I'm encountering a challenge whe ...

Unable to retrieve files from public folder on express server using a React application

The Issue When trying to render images saved on the backend using Express, I am facing a problem where the images appear broken in the browser. Despite looking for solutions to similar issues, none have resolved the issue for me. Specifics In my server.t ...

Having trouble accessing PhpMyAdmin 4.7.2 with PHP 7.0 on Nginx? Hit a roadblock with an "

I was encountering an issue when trying to access phpmyadmin. Although I had successfully installed php7.0, nginx, and phpmyadmin 4.7.2 by downloading the file, unzipping it, putting it in /usr/share/phpMyAdmin, and granting permission 0755, I was unable t ...

Numerous Places To Locate

Utilizing eloquent to filter a collection of products: Product::whereIn('color', $color)->whereIn('size', $size)->whereIn('price', $price)->get(); Each variable mentioned above represents an array of ids. $color = ...

Utilizing Angular2 with Webpack in Visual Studio 2015

Is there a way to utilize Visual Studio 2015 alongside Webpack and Angular2? I have successfully created an Angular2 App with VS, but now that I've added Webpack to build my app, I would like to debug all of my code using IIS Express. I want to be abl ...

CakePHP 3 feature: Utilizing a single related table to populate various dropdowns

Is there a way to use the same dropdown twice and ensure it functions correctly when saving records in Cake 3? In this scenario, the related table is 'responsible_people' and the referencing table is 'organisation_details'. The foreign ...

Experiencing a shortage of memory while generating CSV files

I am currently working on a project that requires writing code to compile a month's worth of data into a CSV file. The dataset consists of approximately 112,000 lines with 47 cells of data per line. However, I am facing memory constraints while tryin ...

Is it necessary to use escape_string for a json_encoded object?

I am trying to save a JSON object in my database: $jsonString='{"test": [{"name":"dave","user":"dan"}]}'; $encodedJson=json_encode($jsonString); $connection=Database::getInstance(); $escapedJson=mysqli_real_escape_string($connection->c ...

Forecastable Unpredictable Sequencing in MySQL

I am struggling to find a solution to my current issue. Currently, I am outputting a table from a MySQL database in a somewhat random order. Although there is a formula that uses the RAND() function, so it's not completely random. However, I want to ...

TSX implementation of a paginator with an ellipse in the center

Looking to add ellipses in the Pagination, specifically when there are more than 10 pages (e.g., 1 2 3 4 ... 11 12 13 14). I've tried various methods but need guidance as a beginner. Can anyone suggest changes based on my code to help me achieve this? ...

Executing an individual .ts file within a Next.js application using ts-node for the purpose of testing

I'm attempting to execute a single ES module .ts file within a Next.js project using the default configuration for quick debugging: npx ts-node lib/my_module.ts However, I encounter the following error: Warning: To load an ES module, set "type&q ...