3

我正在使用graphql,sequelizegraphql-sequelize, 在解决“IS A”关系时遇到了一些麻烦。

我的续集模型如下:

// models.js

// User table
let User = sequelize.define('user', {
    id: Sequelize.INTEGER
    name: Sequelize.STRING
});

// Patient table
let Patient = sequelize.define('patient', {
    bloodType: Sequelize.STRING
});
// Defines "IS A" relationship: [Patient] IS A [User]
Patient.belongsTo(models.User, {
    foreignKey: {
      name: 'id',
      type: DataTypes.INTEGER,
      primaryKey: true
    },
    foreignKeyConstraint: true
})

// Doctor table
let Doctor = sequelize.define('doctor', {
  registry: Sequelize.STRING
});
// Defines "IS A" relationship: [Doctor] IS A [User]
Doctor.belongsTo(models.User, {
    foreignKey: {
      name: 'id',
      type: DataTypes.INTEGER,
      primaryKey: true
    },
    foreignKeyConstraint: true
})

这是我的 graphql 架构:

// graphql.js
import resolver from 'graphql-sequelize';
import * as models from './models';

let userType = new GraphQLObjectType({
    name: 'User',
    fields: {
        id: { type: new GraphQLNonNull(GraphQLInt) },
        name: { type: GraphQLString }
    }
});

let patientType = new GraphQLObjectType({
    name: 'Patient',
    fields: {
        id: { type: new GraphQLNonNull(GraphQLInt) },
        bloodType: { type: GraphQLString },
        user: {
            type: new GraphQLNonNull(userType),
            // IMPORTANT!
            // How can I call resolver if I don't have a assotiation property like Patient.User?
            resolve: resolver()
        }
    }
});

// [doctorType omitted]

let schema = new GraphQLSchema({
  query: new GraphQLObjectType({
    name: 'Query',
    fields: {
        users: {
            type: userType,
            resolve: resolver(models.User)
        },
        patients: {
            type: patientType,
            resolve: resolver(models.Patient)
        }
        // [doctor field omitted]
    }
  })
});

resolver在架构(users和)的字段上调用该方法patients可以正常工作,但我的问题是如何调用解析器patientType以返回其用户,因为我没有关联属性。

谢谢。

4

1 回答 1

0

正如 mickhansen 在这个问题上提到的,所有 sequelize 关联调用都返回一个关联引用。

我存储了从 返回的引用belongsTo,如上图:

 models.Patient.User = Patient.belongsTo(models.User, {
    foreignKey: {
      name: 'id',
      type: DataTypes.INTEGER,
      primaryKey: true
    },
    foreignKeyConstraint: true
})

然后在resolve函数中使用它:

import * as models from '../path/models'

let patientType = new GraphQLObjectType({
    name: 'Patient',
    fields: {
        id: { type: new GraphQLNonNull(GraphQLInt) },
        bloodType: { type: GraphQLString },
        user: {
            type: new GraphQLNonNull(userType),
            resolve: resolver(models.default.Patient.User)
            // alternatively you could the following as sequelize always stores assotiations in associations
            // resolve: resolver(models.default.Patient.associations.User)
        }
    }
});
于 2016-04-13T02:08:13.213 回答