How to populate relation of already populated relation?

I have picked prisma2 as ORM for my new project.

I run into one consideration, how could I load relation of relation?

For example I have such table definitions:

model Brand {
  id      Int     @id @default(autoincrement())
  name    String  @unique
  addedBy User    @relation(fields: [userId], references: [id])
  userId  Int
  models  Model[]
}

model Model {
  id      Int    @id @default(autoincrement())
  name    String
  addedBy User   @relation(fields: [userId], references: [id])
  userId  Int
  Brand   Brand? @relation(fields: [brandId], references: [id])
  brandId Int?
  Car     Car[]
}

model Car {
  id                           Int      @id @default(autoincrement())
  plateCode                    String
  vinCode                      String   @unique
  addedBy                      User     @relation(fields: [userId], references: [id])
  userId                       Int
  ownedByCompany               Company  @relation(fields: [companyId], references: [id])
  companyId                    Int
  model                        Model    @relation(fields: [modelId], references: [id])
  modelId                      Int
  year                         Int
  acquiredDate                 DateTime
  insuranceValidFrom           DateTime
  insuranceExpiresOn           DateTime
  technicalInspectionValidFrom DateTime
  technicalInspectionExpiresOn DateTime
}

When I want to retrieve my data I am getting this response:

[
    {
        "id": 1,
        "plateCode": "XXQ:000",
        "vinCode": "ZXQQQQQQQQQQQQQQQQQQQ",
        "userId": 1,
        "companyId": 1,
        "modelId": 1,
        "year": 2004,
        "acquiredDate": "2021-12-15T21:02:57.206Z",
        "insuranceValidFrom": "2020-02-01T21:02:57.206Z",
        "insuranceExpiresOn": "2023-02-01T21:02:57.206Z",
        "technicalInspectionValidFrom": "2021-06-25T21:02:57.206Z",
        "technicalInspectionExpiresOn": "2023-06-25T21:02:57.206Z",
        "model": {
            "id": 1,
            "name": "525i",
            "userId": 1,
            "brandId": 1
        }
    }
]

Is there a way to populate brandId in similar fashion with include object? Or maybe I could define virtual / computed fields within schema definition?

I know that I could transform / populate that field with second call to db but just thinking whether there is a convenient way to do it. Any help would be appreciated. :)


Solution 1:

Just use include for every relation, like that:

  prisma.car.findMany({
    include: {
      model: {
        include: {
          Brand: true,
        },
      },
    },
  });

More info in the docs

If you just want some fields, not all of them, then you can use select in the same way. Although you cannot mix them.

Note: your Brand field starts with uppercase, you probably want to fix it to be consistent