带有sequelize连接外键的graphql

Hid*_*ide 5 sequelize.js graphql

我用graphql制作了简单的board api系统。

我使用 sequelize(version 4) 连接到数据库。

[schema.graphql]

type Article {
    article_no: Int!
    subject: String!
    content: String!
    createdAt: String!
    updatedAt: String!
    comment: String
}

type Comment {
    article_no: Int!
    content: String!,
    createdAt: String!
}

type Query {
    articles: [Article]!
    article(article_no: Int!): Article
    comments: [Comment]!
    comment(article_no: Int!): Comment
}

type Mutation {
    createArticle(subject: String!, content: String!, password: String!): Boolean!
    createComment(article_no: Int!, content: String!, password: String!): Boolean!
}
Run Code Online (Sandbox Code Playgroud)

[解析器.js]

import { Article, Comment } from './db';

const resolvers = {
    Query: {
        articles: async () => {
            return Article.all();
        },
        article: async(_, args) => {
            return Article.find({
                where: args.article_no,
            });
        },
        comments: async () => {
            return Comment.all();
        },
        comment: async(_, args) => {
            return Comment.find({
                where: args.article_no
            });
        }
    },
    Mutation: {
        createArticle: async (_, args) => {
            try {
                const article = await Article.create({
                    subject: args.subject,
                    content: args.content,
                    password: args.password
                });
                return true;
            } catch(e) {
                return false;
            }
        },
        createComment: async(_, args) => {
            try {
                const comment = await Comment.create({
                    article_no: args.article_no,
                    content: args.content,
                    password: args.password
                })
                return comment;
            } catch(e) {
                return false;
            }
        }
    }
}

export default resolvers;
Run Code Online (Sandbox Code Playgroud)

[db.js]

const Sequelize = require('sequelize');
import config from '../config/config';

const db = new Sequelize(config.DB, config.USER, config.PASS, {
    host: 'localhost',
    dialect: 'mysql'
})

export const Article = db.define('article', {
    article_no: {
        type: Sequelize.INTEGER,
        primaryKey: true,
        autoIncrement: true
    },
    subject: {
        type: Sequelize.STRING(30),
        allowNull: false
    },
    content: {
        type: Sequelize.STRING(100),
        allowNull: false
    },
    password: {
        type: Sequelize.STRING(20),
        allowNull: false
    },
    comment: Sequelize.STRING
}, {
    freezeTableName: true,
    timestamps: true,
    underscored: true
})

export const Comment = db.define('comment', {
    content: {
        type: Sequelize.STRING(150),
        allowNull: false
    },
    password: {
        type: Sequelize.STRING(20),
        allowNull: false
    },
}, {
    freezeTableName: true,
    timestamps: true,
    underscored: true
})

Article.hasMany(Comment, {
    foreignKey: 'article_no',
    scope: {
        comment: 'comment'
    }
})
Comment.belongsTo(Article, {
    foreignKey: 'article_no',
    targetKey: 'article_no',
    allowNull: false,
    as: 'comment'
});
db.sync()
.then(console.log('[*] DB Sync Done'))
Run Code Online (Sandbox Code Playgroud)

Article并且Comment是 1:N 关系。

所以我设置hasManyArticle并设置belongsToComment

也将评论作为评论并将其包含在文章的范围内。

但是当我请求查询时{ article(id:1) { subject, comment } }

评论返回空。

我参考文档http://docs.sequelizejs.com/manual/tutorial/associations.html#foreign-keys并遵循。

但它不起作用。

我的预期结果在这里:

{
  "data": {
    "article": {
      "subject": "test",
      "comment": {
           "article_no":1,
           "content: "first comment",
           "created_at": "2018010101001",
           # every comment related article is here
      }
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

当前结果在这里:

{
  "data": {
    "article": {
      "subject": "test",
      "comment": null
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

我想显示与特定文章相关的所有评论。

有什么解决办法吗?

谢谢。

Dan*_*den 4

一些注意事项可以帮助您走上正轨:

定义关系时,请记住,您正在调用其方法的模型是您要有效添加属性的模型。例如,如果您调用Article.hasMany(Comment),这将在模型上创建一个comments属性Article并影响Comment模型。同样,调用将在模型上Comment.belongsTo(Article)创建属性并且不会影响模型。articleCommentArticle

请注意,即使创建了关系,如果您希望在查询文章时包含关联的评论(反之亦然),则必须传入适当的include选项。这可以直接在查询调用中完成,即

Article.findAll({ include: [Comment] })
Run Code Online (Sandbox Code Playgroud)

或者可以是范围的一部分,例如默认范围。范围可以设置为模型定义的一部分,或者通过调用事后添加addScope。例如,您可以这样做:

Article.addScope('defaultScope', {
  include: [Comment],
}, { override: true })
Run Code Online (Sandbox Code Playgroud)

注意:override这里是必需的,因为默认范围已经存在。要查询关联的模型,您的查询调用或您使用的范围必须包含适当的include数组。关联也有“范围”的概念,但它与模型的范围不同。请参阅此处的文档以了解差异的讨论。

最后,当将where选项传递给您的find调用时,您应该确保它包含您要查询的属性名称,即

Article.find({ where: { article_no: args.article_no } })

// or possibly even
Article.find({ where: args })
Run Code Online (Sandbox Code Playgroud)