Remove the Prisma self-referencing relationship (one-to-many)

I'm working with this particular prisma schema:

model Directory {
  id                String      @id @default(cuid())
  name              String?
  parentDirectoryId String?
  userId            String
  parentDirectory   Directory?  @relation("parentDirectoryId", fields: [parentDirectoryId], references: [id], onDelete: NoAction, onUpdate: NoAction)
  user              User        @relation(fields: [userId], references: [id], onDelete: Cascade)
  quizess           Quiz[]
  subDirectory      Directory[] @relation("parentDirectoryId")

  @@index([parentDirectoryId])
  @@index([userId])
}

The concept behind it: A folder can exist either at the root level (parentDirectoryId = null) or have several additional directories.

Question is, how do I delete a directory that contains other directories?

When attempting to use prisma.delete, I encounter the following issue:

Invalid prisma.directory.delete()

The requested operation would violate the necessary relation 'parentDirectoryId' between the Directory and Directory models.`

Tried setting onDelete: Cascade, onUpdate: Cascade without success

Answer №1

Give this a shot:


let folders = await this.prisma.folder.findFirst({
        where: { id: directory.id },
        include: { subFolder: true },
      });

prisma.folder.update({
   data: {
           subFolder: {
               disconnect: folders.subFolder.map((e) => {
                  return { id: e.id };
               }),
            },
          },
})

The folder is the primary folder.

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

Adaptable images - Adjusting image size for various screen dimensions

Currently, my website is built using the framework . I am looking for a solution to make images resize based on different screen sizes, such as iPhones. Can anyone suggest the simplest way to achieve this? I have done some research online but there are t ...

Tips for attaching event listeners to custom elements

Let's suppose I create a Vue component called Checkbox.vue that contains the following code. <template> <div class="checkbox"> <input id="checkbox" type="checkbox"> <label for="checkbox">Label</label> ...

Parsing of the module has failed due to the presence of an unexpected character '' while attempting to import a video file

Trying to create a video player in NextJS using TS. I brought in a video file from my src/assets folder and encountered an error. Error - ./src/assets/video.mp4 Module parse failed: Unexpected character '' (1:0) You may need an appropriate load ...

Showing Firebase messages in a NativeScript ListView in an asynchronous manner

I am currently struggling to display asynchronous messages in a ListView using data fetched from Firebase through the popular NativeScript Plugin. While I have successfully initialized, logged in, and received the messages, I'm facing challenges in ge ...

Retrieve all users along with their respective posts, ensuring that each post is also accompanied by its corresponding comments in

In my Laravel project, I have set up Eloquent models for User, Post, and Comment. The relationships are as follows: User model public function posts(){ return $this->hasMany('App\Post'); } public function comments(){ return $t ...

JavaScript scroll event not firing

I have searched multiple questions on SO to avoid duplication, but none of the solutions worked for me. My goal is to toggle the visibility of a button based on scroll position. I tried creating a scroll event listener to trigger a function that checks th ...

Guide on transferring object between two $states using ui-router

Visit this link for more information Expected Behavior Upon logging in, selecting a Ticker button is expected to trigger the display of matching Tags for that specific Ticker. Actual Results However, upon clicking a Ticker button after logging in, the ...

Save an array of messages by making separate API calls for each one

I have a function that makes an API call to retrieve a list of message IDs. Here is the code: function getMessageList(auth) { api.users.messages.list({ auth: auth, userId: 'me', }, function(err, response) { if (er ...

CLI package enables exporting API facilities

I have a mono repository containing a CLI package (packages/cli) and a web application (apps/web). I want to utilize the public API of the CLI within the web app. The CLI package is packaged with tsup: export default defineConfig({ clean: false, dts: ...

Developing an Angular filter using pipes and mapping techniques

I am relatively new to working with Angular and I have encountered a challenge in creating a filter for a specific value. Within my component, I have the following: myData$: Observable<MyInterface> The interface structure is outlined below: export ...

Encountering a problem with Angular 11 SSR after compilation, where the production build is causing issues and no content is being displayed in

{ "$schema":"./node_modules/@angular/cli/lib/config/schema.json", "version":1, "newProjectRoot":"projects", "projects":{ "new-asasa":{ "projectType": ...

The dictionary of parameters includes an empty value for the parameter 'imageWidth', which is of a non-nullable type 'System.Int32'

I am facing an issue with a function that executes an ajax call to an ActionResult. It sends a base64 string of an uploaded image along with some additional parameters containing information about the dimensions of the image. The data is sent to the server ...

NextJS Router delays data reloading until page receives focus

Struggling with creating an indexing page in NextJS. Attempting to retrieve the page number using the router: let router = useRouter() let page = isNaN(router.query.page) ? 1 : parseInt(router.query.page); This code is part of a React Query function withi ...

Reloading a page will display [object CSSStyleDeclaration]

Upon editing content and saving changes, instead of displaying my updated content when refreshing the page, it shows [object CSSStyleDeclaration]. function newElement() { let li = document.createElement("li"); let inputvalue = document.querySelector ...

Passing an array of selected values from Vue.js to a text area and adding them to the existing content

I'm facing a situation and I could really use some assistance. The image shows that there is a multiple select box on the left with numbers, and a text box on the right. My goal is to allow users to click on the house numbers in the select box and hav ...

How can one use an Angular Route to navigate to a distinct URL? Essentially, how does one disable matching in the process?

I'm working on a front-end Angular application and I need to add a menu item that links to an external website. For example, let's say my current website has this URL: And I want the menu item in my app to lead to a completely different website ...

Retrieving input values with JQuery

HTML <td data-title="Quantity"> <div class="clearfix quantity r_corners d_inline_middle f_size_medium color_dark m_bottom_10"> <button class="btn-minus bg_tr d_block f_left" data-item-price="8000.0" data-direction= ...

Handsontable: A guide on adding up row values

I have a dynamic number of columns fetched from the database, making it impossible to predict in advance. However, the number of rows remains constant. Here is an illustration: var data = [ ['', 'Tesla', 'Nissan', & ...

Evaluating the functionality of Express Js Server with mocha and chai

I'm currently struggling to properly close the server connection in my Express server when testing it with Mocha and Chai. It seems that even after the test is completed, the server connection remains open and hangs. Index.js const express = require( ...

Guide to showcasing images dynamically within a table

I am currently working on a dynamic table that updates its data using a script. My goal is to also display corresponding images of the groups next to their names in the table. Whenever the group names change, I want the images to change as well. The funct ...