如何使用Prisma查询特定登录用户的交易记录?
查询当前登录用户的交易记录(Prisma实现)
先说明现有Schema的局限
你的Transaction模型目前没有直接关联到User,只能通过关联的Budget间接关联用户。如果存在未绑定Budget的交易,现有Schema没法判断这些交易属于哪个用户,这类交易就无法被正确过滤。所以优先推荐你优化Schema,之后再写查询逻辑。
方案一:优化Schema(推荐)
给Transaction模型添加userId字段和对应的User关联,这样无论交易是否绑定预算,都能直接归属到创建它的用户:
model Transaction { id String @id @default(uuid()) description String amount Float budgetId String? budget Budget? @relation(fields: [budgetId], references: [id]) emoji String? createdAt DateTime @default(now()) // 新增关联用户的字段 userId String user User @relation(fields: [userId], references: [id]) }
修改后运行prisma migrate dev命令更新数据库结构。
对应的查询代码
假设你已经通过认证流程拿到了当前登录用户的ID(存在currentUserId变量中),直接查询即可:
// 获取当前用户的所有交易,可按需关联预算信息 const userTransactions = await prisma.transaction.findMany({ where: { userId: currentUserId }, // 可选:如果需要显示交易所属的预算信息,加上include include: { budget: true } });
方案二:基于现有Schema的查询(不修改Schema)
如果暂时不想修改Schema,只能通过Budget的关联来过滤交易,但无法处理未绑定Budget的交易(这类交易无法判断归属,会被排除):
const currentUserId = "替换为当前登录用户的实际ID"; const userTransactions = await prisma.transaction.findMany({ where: { // 只查询属于当前用户预算下的交易 budget: { userId: currentUserId } }, // 可选:关联显示预算信息 include: { budget: true } });
注意
用这个方案的话,所有未绑定Budget的交易都会被过滤掉,因为没有任何字段能证明它们属于当前用户。
内容的提问来源于stack exchange,提问作者Mohamed
相关产品推荐
相关产品推荐

