t3 stack - Prisma user name from user id

Hello, I have Prisma schema like this and I would like to get username for the post. Now I have userId but how I get username from that? I have username on my database so I should be able to move it to the session? Using client provider with t3 stack and on my session I have now id and email but how to save it to database(?)
model User {
id String @id @default(cuid())
username String? @unique
email String? @unique
emailVerified DateTime?
password String
image String?
posts Post[]
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
}

model Post {
id String @id @default(cuid())
content String
user User @relation(fields: [userId], references: [id])
userId String
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
}
model User {
id String @id @default(cuid())
username String? @unique
email String? @unique
emailVerified DateTime?
password String
image String?
posts Post[]
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
}

model Post {
id String @id @default(cuid())
content String
user User @relation(fields: [userId], references: [id])
userId String
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
}
My trpc mutation:
create: protectedProcedure
.input(newPostSchema)
.mutation(async ({ input, ctx }) => {
const post = await ctx.prisma.post.create({
data: {
userId: ctx.session.user.id,
content: input.content,
},
});

return post;
}),
});
create: protectedProcedure
.input(newPostSchema)
.mutation(async ({ input, ctx }) => {
const post = await ctx.prisma.post.create({
data: {
userId: ctx.session.user.id,
content: input.content,
},
});

return post;
}),
});
2 Replies
Neto
Neto•2y ago
include: {
user: {
select: {
username: true
}
}
}
include: {
user: {
select: {
username: true
}
}
}
rocawear
rocawear•2y ago
Thanks a lot, works like charm! 🙂
Want results from more Discord servers?
Add your server