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
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:
which should return sth like: