Prisma Multiple 1-n relations on same model

Viewed 351

I'm trying to make a model so that a user can own multiple Titles and equip one of them.

The problem is that it does register on the title side, but it does not on the individual user side when I try to query its current title.

The following is how I've built it :

model User {
  id          String   @id @default(cuid())
  titles            Title[]    @relation("titles")
  currentTitle      Title?     @relation("currentTitle", fields: [currentTitleId], references: [id])
  currentTitleId    String?
}

model Title {
  id           String  @id @default(cuid())
  name         String?
  users        User[]  @relation("titles")
  currentUsers User[]  @relation("currentTitle")
}

Is my schema right or did I miss something ? Thanks for your help !

1 Answers

Your model file looks correct. This is a sample code to find currentTitle assigned to User.

import { PrismaClient } from '@prisma/client';

const prisma = new PrismaClient();

async function main() {
  const user = await prisma.user.create({
    data: {},
  });

  console.log(user);

  const title = await prisma.title.create({
    data: {
      name: 'Prisma',
    },
  });

  console.log(title);

  const assignTitle = await prisma.user.update({
    where: {
      id: 'cl4e0gqai0000op78b2apaere',
    },
    data: {
      currentTitleId: 'cl4e0gqbm0007op78xusxlkf7',
    },
  });

  console.log(assignTitle);

  const getCurrentTitle = await prisma.user.findFirst({
    where: {
      id: 'cl4e0gqai0000op78b2apaere',
    },
    select: {
      currentTitle: true,
    },
  });

  console.log(getCurrentTitle);
}

main()
  .catch((e) => {
    throw e;
  })
  .finally(async () => {
    await prisma.$disconnect();
  });

Here's the response:

{ currentTitle: { id: 'cl4e0gqbm0007op78xusxlkf7', name: 'Prisma' } }
Related