Prisma is reporting a failure in enforcing uniqueness constraints, despite the absence of any unique fields defined in the schema

I am currently utilizing prisma in my project, which consists of three models:

model User {
  id               String            @id @default(cuid())
  name             String            @unique @db.VarChar(35)
  email            String            @unique @db.VarChar(512)
  password         String            @db.VarChar(1024)
  details          String            @default("") @db.VarChar(512)
  avatar           String            @default("/default-avatar.svg") @db.VarChar(150)
  activity         String            @default("Online") @db.VarChar(25)
  likes            Int               @default(0)
  suggestions      Boolean           @default(false)
  verified         Boolean           @default(false)
  blockedUsers     BlockedUser[]
  comments         Comment[]
  communities      Community[]
  communityMembers CommunityMember[]
  followers        Follower[]
  friends          Friend[]
  messages         Message[]
  posts            Post[]
  openDMs          DM[]
  interests        UserInterest[]

  @@map("user")
}
model Community {
  id          String              @id @default(cuid())
  title       String              @unique @db.VarChar(35)
  details     String              @db.VarChar(512)
  memberID    String?
  membersUser User[]
  members     CommunityMember[]
  interests   CommunityInterest[]
  posts       Post[]

  @@map("community")
}
model CommunityMember {
  id          String    @id @default(cuid())
  nickname    String?
  userID      String
  communityID String
  user        User      @relation(fields: [userID], references: [id])
  community   Community @relation(fields: [communityID], references: [id])
  owner       Boolean

  @@map("community_member")
}

A specific route in my backend is causing an issue. It involves creating a new table for community members using the prisma client and connecting existing users and communities by their IDs. However, this process results in an error message:

Unique constraint failed on the constraint: community_member_communityID_key

Shown below is the code snippet responsible for adding a community member:

await prisma.communityMember.create({
  data: {
    nickname: response.account.name,
    user: {
      connect: { id: response.account.id }
    },
    community: {
      connect: { id: communityID }
    },
    owner: false
  }
});

I have attempted to drop the database and reset prisma migrations, but the problem persists. Upon inspecting the MySQL table, it appears that both the communityID and userID fields are set as unique, leading me to suspect an issue with prisma migrate. Does anyone have insight into what might be causing this issue and how I can create these fields without encountering uniqueness constraints?

Answer №1

Have you considered using the create method instead of connect in this scenario? The documentation at https://www.prisma.io/docs/concepts/components/prisma-client/relation-queries#nested-writes suggests that nested writes should use the create method:

await prisma.communityMember.create({
    data: {
      nickname: response.account.name,
      user: {
        create: [
            {id: response.account.id}
        ]
      },
      community: {
        create: [
            {id: communityID}
        ]
      },
      owner: false
    }
})

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

Distinguishing Between Identifying and Non-Identifying Relationships in SQL

I recently made the switch from using phpMyAdmin to MySQL Workbench for managing EER diagrams. However, terms like Identifying & Non-Identifying relationships are new to me and I'm struggling to grasp the concept. After some online research and readi ...

PHP script that creates text files by retrieving data from a MySQL database table

Recently, I have developed a PHP code that is designed to create a text file and store the information from a MySQL table row by row. The code I have written is as follows: <?php session_start(); include "functions.php"; db_connect(); $winners=mysql_qu ...

Using the LOWER function in my SQL query is causing my index to be ineffective

Is there a way to make my query case-insensitive for column names without using the lower method in SQL? Select * from User where lower(lusername)= 'abdel' I need the flexibility to search for column names regardless of case sensitivity (e.g. ...

npm encountered an issue when attempting to install a package from a local directory: EISDIR: illegal operation on a directory, read

While attempting to add my compiled TypeScript output as a local package using npm, this error appears: $ npm install --save ../app/out npm ERR! eisdir EISDIR: illegal operation on a directory, read npm ERR! eisdir This is most likely not a problem wit ...

Adjust the timezone in PHP according to the user's preference

Is it possible to dynamically display the timezone of the user who is visiting my website? I created a comment section where I want the timestamps of comments to be shown based on the user's local time. I have already implemented the date and time fun ...

Exploring the world of table connection with PHP and MySql

https://i.sstatic.net/qYEmX.png https://i.sstatic.net/7y3J4.png I need to merge data from two tables and extract amount details from the first table based on IDs in the "left & right" columns of the second table. ** EDIT: Instead of images, here is the ...

Tips for retrieving a child component's content children in Angular 2

Having an issue with Angular 2. The Main component displays the menu, and it has a child component called Tabs. This Tabs component dynamically adds Tab components when menu items are clicked in the Main component. Using @ContentChildren in the Tabs comp ...

Checking for Object Equality in TypeScript

I'm working on a TypeScript vector library and encountered my first failed test. The issue revolves around object equality in TypeScript/JavaScript, and despite searching through TypeScript's official documentation (http://www.typescriptlang.org ...

Generating MySQL Event on-the-fly

My website allows users to organize events, and I am in need of a solution to automatically delete these events from the MySQL database once they have taken place. Therefore, I am attempting to set up a system where an event is scheduled in the database to ...

Storing a user's data in an MySQL database for future reference

In the application I'm working on, a user can login and then be directed to the dashboard. While I've successfully implemented the login functionality, my next objective is to store the user's information for future use in other forms. For ...

Angular and TypeScript allow for dynamic binding after a click event

My text has annotations marked dynamically with spans. By using the 'addClickEvent' function, I'm able to add a click-event to provide users with more information when they click on the annotations. Although I can retrieve all the informatio ...

Retrieve the public variable of a child page from the parent page

Is there a way to access the public variable offlineArticlesCount from an inner child page within the parent page? Please note: Each of the 3 components mentioned below has its own set of modules. myPage.html - Parent Page <picks *ngFor="let pick of ...

What is the process for creating a conditional statement to choose multiple items from a column in MySQL Workbench?

I am brand new to coding and I am attempting to create a program that will identify the participant_ids of individuals who have responded to both question_id = '1' and question_id = '10', while also counting the results. SELECT partici ...

Tailored class designed to handle navigation between preceding and subsequent items

I am in the process of developing a PHP page that includes fields for First Name, Last Name, Address, ZIP, and various others. My goal is to incorporate an 'Add More' button, a 'Previous' button, and a 'Save' button into the p ...

Azure functions encountered an issue: TypeError - it seems that the connection.query function is not recognized

Having a slight issue with my Azure function that is supposed to retrieve all data from a SQL table. The connection to the database is successful, but whenever I attempt to run the get request, it results in an error Exception: TypeError: connection.query ...

Surprising appearance of '$fname' (T_VARIABLE)?

I'm having trouble understanding the type of error I encountered. I am attempting to input data into a MySQL database using PHP on a XAMPP server. $data = 'UPDATE `personnel` SET fname='$fname', mname='$mname', lname='$l ...

Inability to assign a value to an @input within an Angular project

I recently started using Angular and I'm currently trying to declare an input. Specifically, I need the input to be a number rather than a string in an object within an array. However, I'm encountering difficulties and I can't figure out wha ...

Encountered Axios Error: Network Connection Failure and CORS Challenge while working in React

I'm attempting to call the API located at . Unfortunately, I am encountering an error in the console of the developer tools: Access to XMLHttpRequest at 'https://api.wisecapitals.com/cronjobs/fetchXERate' from origin 'http://localho ...

Unable to sort dates using arrays on IOS

Currently, I am retrieving data from my server and storing it in a variable named "items". Whenever I execute the following code: if (this.items) { this.items.sort(function (a, b) { return +new Date(b.datum) - ...

Error: The type 'Promise' cannot be assigned to the type 'Model' in Angular 2 when working with Firebase

I have a method in my bug service that retrieves a single record from Firebase based on the bugId provided: // This method is located in bugservice.ts getBug(bugId: string): Promise<Bug> { return this.bugsDbRef .child(bugId) ...