如何解决Apollo,Sequelize-简单的“ belongsTo”关联返回null
尝试为我的阿波罗graphql api设置一个简单的关联。我有两个表:user
和role
。每个用户都有一个role_id
列,该列引用role
表中的主键。
每当我查询:
{
users{
id,email,role{
id
}
},}
我收到以下错误:"Cannot return null for non-nullable field User.role.",
我不熟悉续集/阿波罗,但看不到我要去哪里。
models/user.js
'use strict';
const { Model } = require('sequelize');
module.exports = (sequelize,DataTypes) => {
class User extends Model {
/**
* Helper method for defining associations.
* This method is not a part of Sequelize lifecycle.
* The `models/index` file will call this method automatically.
*/
static associate(models) {
// define association here
User.belongsTo(models.Role);
}
};
User.init({
email: DataTypes.STRING,password: DataTypes.STRING,},{
sequelize,tableName: 'user',schema: 'auth',modelName: 'User',timestamps: false,underscored: true,});
return User;
};
models/role.js
'use strict';
const { Model } = require('sequelize');
module.exports = (sequelize,DataTypes) => {
class Role extends Model {
/**
* Helper method for defining associations.
* This method is not a part of Sequelize lifecycle.
* The `models/index` file will call this method automatically.
*/
static associate(models) {
// define association here
Role.hasMany(models.User)
}
};
Role.init({
name: DataTypes.STRING,isDefault: {
type: DataTypes.BOOLEAN,field: 'is_default'
},tableName: 'role',modelName: 'Role',});
return Role;
};
这些模型在我的models/index.js
中与以下代码段相关联:
...
Object.keys(db).forEach(modelName => {
if (db[modelName].associate) {
db[modelName].associate(db);
}
});
// sync models - modifies the database to match every model
sequelize.sync({ alter: true,match: /-apollo$/ })
...
这是我的:resolvers/user.js
module.exports = {
Query: {
users: async (parent,args,{ models }) => {
return await models.User.findAll({ include: [{model: models.Role}] });
},user: async (parent,{ id },{ models }) => {
return await models.User.findByPk(id);
},};
任何帮助将不胜感激!
编辑:我创建了一个新数据库,并将sequelize.sync()
添加到了models/index.js
中,以确保这不是由于数据库设置中的某些错误引起的。
解决方法
找到了解决方案。我的问题是,sequelize自动为关联命名,在我的情况下这是意外的,因此我的架构与关联的实际名称不匹配,从而导致空值。
要解决此问题,我在关联中添加了as: "something"
道具:
resolvers/user.js
module.exports = {
Query: {
users: async (parent,args,{ models }) => {
return await models.User.findAll({ include: [{model: models.Role,as: 'role'}] });
},user: async (parent,{ id },{ models }) => {
return await models.User.findByPk(id);
},},};
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。