Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prisma Multiple 1-n relations on same model

Tags:

prisma

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 !

like image 945
Felix Perroud Avatar asked Sep 05 '25 03:09

Felix Perroud


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' } }
like image 77
Nurul Sundarani Avatar answered Sep 08 '25 00:09

Nurul Sundarani



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!