我正在使用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]
}
})
});
在架构(resolver
和users
)字段上调用patients
方法可以正常工作,但我的问题是如何在patientType
中调用解析器返回它的用户,因为我没有关联财产。
感谢。
答案 0 :(得分:0)
正如mickhansen在issue上提到的,所有续集关联调用都会返回一个关联引用。
我存储了从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)
}
}
});