Prisma findMany function is not returning relational data

Viewed 2709

I am trying to populate my data with relational data using Prisma 2.28.0, Here is my

Schema.prisma model below

generator client {
  provider = "prisma-client-js"
}

datasource db {
  provider = "postgresql"
  url      = env("DATABASE_URL")
}

model Product {
  id           Int         @id @default(autoincrement())
  name         String         @db.VarChar(255)
  transactions Transaction[]
}

model Transaction {
  id        BigInt   @id @default(autoincrement())
  quantity  Int
  time      Int
  product  Product? @relation(fields: [productId], references: [id])
  productId Int?
}


the function I am trying to fetch data.

const { PrismaClient }=require("@prisma/client")

const prisma = new PrismaClient()

async function checkPrismaConnection(){
    try {
        const result=await prisma.product.findMany();
        console.log(result);
    }catch (e) {
        console.log(e);
    }
}

 checkPrismaConnection();

OutPut

[
  { id: 1, name: 'John Doe' },
  { id: 2, name: 'Masum' },
  { id: 3, name: 'Rezaul' }
]

Transaction DB result enter image description here

Product DB

enter image description here

I don't know why my findMany() is not retuning relational db data. Thank you

2 Answers

I suggest reading the documentation, especially this chapter and the ones following that. In their example, they have an Author and Post, where Post has an author field pointing at an Author. Their code looks like this:

const getPosts = await prisma.post.findMany({
  where: {
    title: {
      contains: 'cookies',
    },
  },
  include: {
    author: true, // Return all fields
  },
})

The chapter "Include deeply nested relations" a bit lower actually uses a field .category that's also an array, as in your example with .transactions.

You need to explicitly set include to true.

So the code will look like this for you

const { PrismaClient }=require("@prisma/client")

const prisma = new PrismaClient()

async function checkPrismaConnection(){
   try {
    const result=await prisma.product.findMany({
      include: {
        transaction: true,
       },
   });
    console.log(result);
}catch (e) {
    console.log(e);
}
}

 checkPrismaConnection(); 
Related