【发布时间】:2018-09-28 21:41:16
【问题描述】:
假设我有两个对象数组:
let movies = [
{ id: '1', title: 'Erin Brockovich'},
{ id: '2', title: 'A Good Year'},
{ id: '3', title: 'A Beautiful Mind'},
{ id: '4', title: 'Gladiator'}
];
let actors = [
{ id: 'a', name: 'Julia Roberts'},
{ id: 'b', name: 'Albert Finney'},
{ id: 'c', name: 'Russell Crowe'}
];
我想在他们之间建立多对多的关系。从 Vanilla JavaScript 开始,最终在 GraphQL 模式中。
在 JavaScript 中我做了这样的事情:
let movies = [
{ id: '1', title: 'Erin Brockovich', actorId: ['a', 'b'] },
{ id: '2', title: 'A Good Year', actorId: ['b', 'c'] },
{ id: '3', title: 'A Beautiful Mind', actorId: ['c'] },
{ id: '4', title: 'Gladiator', actorId: ['c'] }
];
let actors = [
{ id: 'a', name: 'Julia Roberts', movieId: ['1'] },
{ id: 'b', name: 'Albert Finney', movieId: ['1', '2'] },
{ id: 'c', name: 'Russell Crowe', movieId: ['2', '3', '4'] }
];
let actorIds = [];
let movieIds = [];
for (let m = 0; m < movies.length; m ++) {
for (let i = 0; i < movies[m].actorId.length; i ++) {
actorIds.push(movies[m].actorId[i]);
}
}
for (let a = 0; a < actors.length; a ++) {
for (let i = 0; i < actors[a].movieId.length; i ++) {
movieIds.push(actors[a].movieId[i]);
}
}
for (let a = 0; a < actors.length; a ++) {
for (let i = 0; i < actorIds.length; i ++) {
if ((actors[a].id == 'c') && (actors[a].id == actorIds[i])) {
for (let j = 0; j < movies.length; j ++) {
if (movies[j].id == movieIds[i]) {
console.log(movies[j].title);
}
}
}
}
}
当我在 Node 中运行前面的代码时,终端会返回
A Good Year
A Beautiful Mind
Gladiator
这正是我想要的。
不幸的是,我迷失在 GraphQL 架构中。到目前为止,我所拥有的——当然是在 fields 函数内部——是这样的:
in_which_movies: {
type: new GraphQLList(FilmType),
resolve(parent, args) {
let actorIds = [];
let movieIds = [];
for (let m = 0; m < movies.length; m ++) {
for (let i = 0; i < movies[m].actorId.length; i ++) {
actorIds.push(movies[m].actorId[i]);
}
}
for (let a = 0; a < actors.length; a ++) {
for (let i = 0; i < actors[a].movieId.length; i ++) {
movieIds.push(actors[a].movieId[i]);
}
}
for (var a = 0; a < actors.length; a ++) {
for (var i = 0; i < actorIds.length; i ++) {
if ((actors[a].id == parent.id) && (actors[a].id == actorIds[i])) {
for (var j = 0; j < movies.length; j ++) {
if (movies[j].id == movieIds[i]) {
console.log(movies[j].title);
}
}
}
}
}
return movies[j].title;
}
}
当我在 GraphiQL 中运行以下查询时...
{
actor(id: "c") {
name
in_which_movies {
title
}
}
}
...我有这样的回应:
{
"errors": [
{
"message": "Cannot read property 'title' of undefined",
"locations": [
{
"line": 4,
"column": 3
}
],
"path": [
"actor",
"in_which_movies"
]
}
],
"data": {
"actor": {
"name": "Russell Crowe",
"in_which_movies": null
}
}
}
...这对我来说很奇怪,因为终端响应我的预期
A Good Year
A Beautiful Mind
Gladiator
我想到目前为止我写的所有代码都是无用的,我需要一些新的指导来正确地在 GraphQL 中编写多对多关系。
【问题讨论】:
标签: many-to-many graphql