javascriptnext.jsprisma

prisma : how can i get transactions of a specifc user?


I have the following schema :

model User {
  id            String       @id @default(uuid())
  email         String       @unique
  createdAt     DateTime     @default(now())
  budgets       Budget[]
}

model Budget {
  id           String       @id @default(uuid())
  name         String
  amount       Float
  userId       String
  user         User         @relation(fields: [userId], references: [id])
  emoji        String?   
  transactions Transaction[]
  createdAt    DateTime     @default(now())
}

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())
}

My goal is to make a query that displays ONLY the transactions that the user created when he logged in to the web app, and NOT the transactions created by other users. How can I do that? (I am new to prisma)


Solution

  • const userId = 'userId'; // ID of the user you want to filter
    
    const transactions = await prisma.transaction.findMany({
      where: {
        budget: {
          userId: userId,
        },
      },
    });
    
    1. Uses findMany on Transaction to fetch multiple transactions.
    2. Filters with where to only get transactions where the budget is associated with the specified userId.