skip to Main Content

Please let me ask.

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 this following result.

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

But I’d like to have not only user’s name, in this case "Paul McCartney", but also friends’ id and name like…

{  
  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

2

Answers


  1. 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);
    
    Login or Signup to reply.
  2. Unknown field ‘name’ for select statement on model Friend

    Of course cause Friend doesnt have the name prop you have to get the name from its user prop, basically you have to do this:

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

    which should return sth like:

    {  
      name: 'Paul McCartney',
      {
        friend: [ 
         { userId: 1, user: {name: "Manny"} },
         { userId: 3, user: {name: "Jane" } } 
        ],
      }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search