Search code examples
javascripttypescriptsqliteprisma

How can I get a field with another field which is set foreign key?


schema.prisma:

model User {
  id         Int           @id @default(autoincrement())
  name       String        // Not Null
  self       Friend[]      @relation("self")   
  friend     Friend[]      @relation("friend")  
}

model Friend {
  id         Int        @id @default(autoincrement())
  user       User       @relation("self", fields: [userId], references: [id])
  userId     Int        // Foreign Key
  friend     User       @relation("friend", fields: [friendId], references: [id])
  friendId   Int        // Foreign Key
  // @@unique([userId, friendID]) 
}

sample.tsx:

const friends = await prisma.user.findUnique({
  where: {
    id: userId, // user ID
  },
  select: {
    name: true, // user name
    // Friend Table
    friend: {
      select: {
        userId: true, // friends' ID
      },
    },
  },
});

console.log(friends); 

In sample.tsx I got :

{  
  name: 'Paul McCartney',
  friend: [ { userId: 1 }, { userId: 3 }, { userId: 4 } ]
}

I'd like to have not only user's name, in this case "Paul McCartney", but also friend's id and name :

{  
  name: 'Paul McCartney',
  friend: [ { userId: 1 , name: "John Lennon"}, { userId: 3, name: "Ringo starr" }, { userId: 4, name: "George Harrison" } ]
}

// OR something like...

{  
  name: 'Paul McCartney',
  {
    friend: [ { userId: 1}, { userId: 3 }, { userId: 4 } ],
    name: ["John Lennon", "Ringo starr", "George Harrison"]
  }
}

How should I change sample.tsx?

Prisma : 4.16.0 SQLite : 3.38.2


Solution

  • const friends = await prisma.user.findUnique({
    where: {
      id: userId, // user ID
    },
    select: {
      name: true, // user name
      friend: {
        select: {
          user: {
            select: {
              id: true, 
              name: true 
            }
          }
        }
      }
    },
    });
    
    console.log(friends);