I've implemented a createUser function in my user.server.ts file:
export async function createUser(username: User["username"], email: User["email"], password: string) {
const hashedPassword = await bcrypt.hash(password, 10)
const user = await prisma.user.create({
data: {
email,
username,
role: {
create: {
name: ValidRoles["User"]
}
},
hashed_password: hashedPassword,
},
})
return prisma.userProfile.create({
data: {
user: {
connect: user
},
userId: user.id,
}
})
}
This aligns with the following Schema:
model User {
id Int @id @default(autoincrement())
username String @unique @default("user")
email String @unique
hashed_password String
role Role @relation(fields: [roleId], references: [id]) // Fields: PK, references: FK
roleId Int @default(0)
profile UserProfile @relation(fields: [profileId], references: [id], onUpdate: Cascade)
profileId Int @unique @default(1)
createdAt DateTime @default(now())
updatedAt DateTime @default(now()) @updatedAt
}
model UserProfile {
id Int @id @default(autoincrement())
user User?
userId Int @unique
}
However, when attempting to register a new user, I encounter the following error:
Error:
Invalid `prisma.user.create()` invocation in
app\models\user.server.ts:18:34
15 export async function createUser(username: User["username"], email: User["email"], password: string) {
16 const hashedPassword = await bcrypt.hash(password, 10)
17
→ 18 const user = await prisma.user.create(
Foreign key constraint failed on the field: `User_profileId_fkey (index)`
at Zr.handleRequestError (node_modules\@prisma\client\runtime\library.js:171:6414)
at Zr.handleAndLogRequestError (node_modules\@prisma\client\runtime\library.js:171:5948)
at Zr.request (node_modules\@prisma\client\runtime\library.js:171:5786)
at t._request (node_modules\@prisma\client\runtime\library.js:174:10455)
at createUser (app\models\user.server.ts:18:16)
at action (app\routes\register.tsx:26:9)
at Object.callRouteActionRR (build\server.js:39464:20)
at callLoaderOrAction (build\server.js:38586:18)
at submit (build\server.js:38277:20)
at queryImpl (build\server.js:38240:27)
I believed my relations were correct, but if they are not, could someone provide clarification? If not, what is the issue and how can it be resolved? Any assistance would be greatly appreciated.