I am working on a project. I have a user model as follows
model User {
id Int @id @default(autoincrement())
firstName String?
lastName String?
email String @unique
slug String @unique @default()
}
Okay? I just want whenever I push a user to the database the slug to be set automatically to the id field!
I did this before in row SQL but wondering how to do this with Prisma!
I have searched and didn't find something relevant.
I am using Postgresql as my DB.
any help?
CodePudding user response:
Based on Prisma documentation it should by achievable by
model User {
id Int @id @default(autoincrement())
firstName String?
lastName String?
email String @unique
slug String @unique @default(USER)
}
My only concern is related with different type of those fields.
CodePudding user response:
I have found a solution to my problem. According to this page Prisma Unsupported SQL features
Prisma does not support triggers and procedures!
But they enable you to add these to your migrations! Wonderful!
And, Simply to achieve what I wanted:
run npx prisma migrate dev --create-only
then open the migration file you just created
and add your triggers / procedures:
for my case, I want whenever there is a new user, his slug becomes his id. He can change the slug later.
I added these statements:
CREATE OR REPLACE FUNCTION create_auto_user_slug()
RETURNS trigger
LANGUAGE plpgsql AS
$func$
BEGIN
NEW.slug = NEW.id;
RETURN NEW;
END
$func$;
CREATE TRIGGER auto_user_slug
BEFORE INSERT ON users
FOR EACH ROW
EXECUTE PROCEDURE create_auto_user_slug();
After that, just run npx prisma migrate dev
And now you have the functionality you desired! Great.