philolegein
philolegein

Reputation: 1515

Get created relation on upsert in Prisma

I'm just getting started with Prisma, and have the following schema:

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

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

model Client {
  id        Int     @id @default(autoincrement())
  email     String      @unique
  first     String?
  last      String?
  tickets   Ticket[]
}

model Ticket {
  id        String      @id @default(uuid())
  purchasedAt   DateTime    @default(now())
  pricePaid Int
  currency  String      @db.VarChar(3)
  productId String
  client    Client      @relation(fields: [clientId], references: [id])
  clientId  Int
}

When a client buys a new ticket, I want to create a new ticket entry, and the associated client entry, if the client doesn't exist. Much to my surprise, the following Just Worked:

    const ticketOrder = {
      // details
    };

    const client = await prisma.client.upsert({
      where: {
        email: email,
      }, update: {
        tickets: {
          create: [ ticketOrder ]
        }
      }, create: {
        first: first,
        last: last,
        email: email,
        tickets: {
          create: [ ticketOrder ]
        }
      }
    });

However, what gets returned is just the client entry, and what I need is the newly created ticket entry (actually, just the id of the newly created ticket entry). Is there any way to get that in one go, or do I have to do some sort of query after the upsert executes?

Upvotes: 0

Views: 3139

Answers (1)

some-user
some-user

Reputation: 4894

You can use select or include as you would in a find operation to include referenced objects, e.g.

const client = await prisma.client.upsert({
  where: {
    email: email,
  },
  update: {
    tickets: {
      create: [ ticketOrder ]
    }
  },
  create: {
    first: first,
    last: last,
    email: email,
    tickets: {
      create: [ ticketOrder ]
    }
  },
  include: {
    tickets: true
  }
});

This would return all tickets.

To me, it seems strange to upsert the client, if you primarily want to create at ticket. You could instead create a ticket and create or connect the client:

const ticket = await prisma.ticket.create({
  data: {
    // ...
    client: {
      connectOrCreate: // ...
    }
  },
})

See: https://www.prisma.io/docs/concepts/components/prisma-client/relation-queries#connect-or-create-a-record

Upvotes: 1

Related Questions