Graphql 从Prisma中的多对多表获取元信息
我有这个桌子结构 注意Graphql 从Prisma中的多对多表获取元信息,graphql,apollo,prisma,Graphql,Apollo,Prisma,我有这个桌子结构 注意item\u level键 我需要完成的是将相同的物品附加到许多玩家身上,但每个玩家都可以独立升级物品 这是我能想到的最简单的结构,用sql术语来说,连接表、选择字段和显示这些连接很容易 我的问题是,我正在使用阿波罗graphql和PrismaORM(v^2.18.0),即使我可以得到每个玩家的物品,反之亦然,我也不知道如何包含这个额外的字段 prisma.schema model Player { id Int @id @de
item\u level
键
我需要完成的是将相同的物品附加到许多玩家身上,但每个玩家都可以独立升级物品
这是我能想到的最简单的结构,用sql术语来说,连接表、选择字段和显示这些连接很容易
我的问题是,我正在使用阿波罗graphql和PrismaORM(v^2.18.0),即使我可以得到每个玩家的物品,反之亦然,我也不知道如何包含这个额外的字段
prisma.schema
model Player {
id Int @id @default(id())
items ItemToPlayer[]
}
model Item {
id Int @id @default(id())
players ItemToPlayer[]
}
model ItemToPlayer {
player Player @relation(fields: [playerId], references: [id])
playerId Int
item Item @relation(fields: [itemId], references: [id])
itemId Int
itemLevel Int @default(0)
@@id([playerId, itemId])
}
typeDefs
const typeDefs = gql`
type Player {
id: ID!
items: [Item]
}
type Item {
id: ID!
players: [Player]
}
type ItemToPlayer {
playerId: Int!
itemId: Int!
itemLevel: Int!
}
`;
分解器
const resolvers = {
Player: {
items: (parent, args, context, info) => {
return context.db.item.findMany({
where: {
players: {
some: {
playerId: parent.id
}
}
},
include: {
players: true
}
});
},
},
Item: {
players: (parent, args, context, info) => {
return context.db.player.findMany({
where: {
items: {
some: {
itemId: parent.id
}
}
},
include: {
items: true
}
});
},
},
Query: { /* ... */ },
Mutation: { /* ... */ },
};
这是我希望在查询玩家(包括他们的物品)时得到的结果
{
"data": {
"players": [
{
"id": 1
"items": [
{
"id": 1,
"itemLevel": 2 // <--- This is missing
},
{
"id": 2,
"itemLevel": 3
},
]
},
{
"id": 2
"items": [
{
"id": 1,
"itemLevel": 0 // same item (id: 1) has different level per player
}
]
},
]
}
}
{
“数据”:{
“玩家”:[
{
“id”:1
“项目”:[
{
“id”:1,
“itemLevel”:2/我建议将您的typedef更改为:
const typeDefs = gql`
type Player {
id: ID!
items: [ItemToPlayer]
}
type Item {
id: ID!
players: [ItemToPlayer]
}
type ItemToPlayer {
playerId: Int!
itemId: Int!
itemLevel: Int!
player: Player!
item: Item!
}
`;
然后,您的项目中的玩家
解析器将如下所示:
prisma.player.findMany({
where: {
items: {
some: {
itemId: parent.id,
},
},
},
include: {
items: { include: { item: true } },
},
})
我按照@Ryan在回答中的建议,通过将Item
更改为ItemToPlayer
,并更改我的查询和解析程序来获取元数据
新的项目
分解器
Item: {
players: (parent, args, context, info) => {
return context.db.itemToPlayer.findMany({
where: {
itemId: parent.id
},
include: {
item: true
}
});
},
},
现在我正在查询ItemsToPlayers
表,并返回一个ItemToPlayer
类型,然后我可以从中查询项
CORRECT
query {
players {
id
items {
id
itemLevel
item {
id
}
}
}
}
WRONG
query {
players {
id
items {
id
itemLevel <--- This is wrong as itemLevel
does not exist in Item
}
}
}
将typeDefs改为ItemToPlayer
而不是Item
有帮助,因为我可以在数据库中查询ItemToPlayer,然后在结果中查询该项。嵌套的include
给了我一个错误。我在没有嵌套include的情况下成功地做到了这一点。不过我必须修改查询本身。
{
"data": {
"players": [
{
"id": 1
"items": [
{
"itemLevel": 2
"item": {
"id": 1,
}
},
{
"itemLevel": 0
"item": {
"id": 1,
}
},
]
},
]
}
}