最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

如何使GraphQL架构MySQL的车型?

运维笔记admin7浏览0评论

如何使GraphQL架构MySQL的车型?

如何使GraphQL架构MySQL的车型?

我下表在MySQL的。

用户

CREATE TABLE users(
    id INTEGER AUTO_INCREMENT PRIMARY KEY,
    username VARCHAR(255) UNIQUE NOT NULL,
    email VARCHAR(255) UNIQUE NOT NULL,
    password VARCHAR(100) NOT NULL,
    created_at TIMESTAMP DEFAULT NOW()
);

和帖子

CREATE TABLE posts(
    id INTEGER AUTO_INCREMENT PRIMARY KEY,
    created_by INTEGER NOT NULL,
    created_at TIMESTAMP DEFAULT NOW(),
    post_title VARCHAR(100) NOT NULL UNIQUE,
    post_body VARCHAR(255) NOT NULL,
    slug VARCHAR(100) NOT NULL UNIQUE,
    FOREIGN KEY (created_by) REFERENCES users(id)
);

我使用的NodeJS和MySQL NPM包。我怎样才能使为模特graphQL模式?

我搜索了很多,但没有找到任何解决这个。大多人都在使用sequelize用于这一目的。是不是比MySQL包好?

回答如下:

是的,你可以使用sequelize的ORM graphql连接MySQL数据库

参考: - qazxsw POI

示例模式和解析器给出

Schema.js

http://docs.sequelizejs/manual/installation/getting-started

connectors.js

const typeDefinitions = `



type Author {

  authorId: Int
  firstName: String
  lastName: String
  posts: [Post]

}

type Post {

  postId: Int
  title: String 
  text: String
  views: Int
  author: Author

}

input postInput{
  title: String 
  text: String
  views: Int
}


type Query {

  author(firstName: String, lastName: String): [Author]
  posts(postId: Int, title: String, text: String, views: Int): [Post]

}



type Mutation {

createAuthor(firstName: String, lastName: String, posts:[postInput]): Author

updateAuthor(authorId: Int, firstName: String, lastName: String, posts:[postInput]): String

}


schema {
  query: Query
  mutation:Mutation
}
`;

export default [typeDefinitions];

resolver.js

import rp from 'request-promise';
var Sequelize = require('sequelize');
var db = new Sequelize('test', 'postgres', 'postgres', {
  host: '192.168.1.168',
  dialect: 'postgres',

  pool: {
    max: 5,
    min: 0,
    idle: 10000
  }

});


const AuthorModel = db.define('author', {
  authorId: { type: Sequelize.INTEGER, primaryKey: true, autoIncrement: true, field: "author_id" },
  firstName: { type: Sequelize.STRING, field: "first_name" },
  lastName: { type: Sequelize.STRING, field: "last_name" },
},{
        freezeTableName: false,
        timestamps: false,
        underscored: false,
        tableName: "author"
    });


const PostModel = db.define('post', {
    postId: { type: Sequelize.INTEGER, primaryKey: true, autoIncrement: true, field: "post_id" },
  text: { type: Sequelize.STRING },
  title:  { type: Sequelize.STRING },
  views: { type: Sequelize.INTEGER },
},{
        freezeTableName: false,
        timestamps: false,
        underscored: false,
        tableName: "post"
    });


AuthorModel.hasMany(PostModel, {
    foreignKey: 'author_id'
});
PostModel.belongsTo(AuthorModel, {
    foreignKey: 'author_id'
});

const Author = db.models.author;
const Post = db.models.post;

export { Author, Post };
发布评论

评论列表(0)

  1. 暂无评论