gpt4 book ai didi

node.js - Apollo,Sequelize - 简单的 `belongsTo` 关联返回 null

转载 作者:行者123 更新时间:2023-12-03 22:18:22 26 4
gpt4 key购买 nike

试图在 sequelize 中为我的 apollo graphql api 设置一个简单的关联。我有两个表: userrole 。每个用户都有一个 role_id 列,它引用 role 表中的主键。
每当我查询:

{
users{
id,
email,
role{
id
}
},
}
我收到以下错误: "Cannot return null for non-nullable field User.role.",我是 Sequelize/阿波罗的新手,但无法看出我哪里出错了。 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'
},
}, {
sequelize,
tableName: 'role',
schema: 'auth',
modelName: 'Role',
timestamps: false,
underscored: true,
});

return Role;
};
模型在 my: 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" Prop 添加到了我的关联中: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);
},
},
};

关于node.js - Apollo,Sequelize - 简单的 `belongsTo` 关联返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63723798/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com