用 graphql-sequelize 解决“IS A”关系
Posted
技术标签:
【中文标题】用 graphql-sequelize 解决“IS A”关系【英文标题】:Resolve "IS A" relationship with graphql-sequelize 【发布时间】:2016-07-26 06:36:06 【问题描述】:我正在使用 graphql
、sequelize
和 graphql-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]
)
);
在架构字段(users
和 patients
)上调用 resolver
方法可以正常工作,但我的问题是如何在 patientType
中调用解析器以返回其用户,因为我没有关联属性。
谢谢。
【问题讨论】:
【参考方案1】:正如 mickhansen 在 issue 中提到的,所有 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)
);
【讨论】:
以上是关于用 graphql-sequelize 解决“IS A”关系的主要内容,如果未能解决你的问题,请参考以下文章
用fuser或者lsof解决无法umount问题(device is busy)
运行用例时,报错Unknow Error:Element xxx is not clickable……的解决方法