Apollo,Sequelize - 简单的 `belongsTo` 关联 returns null

Apollo, Sequelize - Simple `belongsTo` association returns null

正在尝试为我的 apollo graphql api 在 sequelize 中设置一个简单的关联。我有两个 table:userrole。每个用户都有一个 role_id 列引用 role table.

中的主键

每当我查询时:

{
  users{
    id,
    email,
    role{
      id
    }
  },
}

我收到以下错误:"Cannot return null for non-nullable field User.role.",

我是 sequelize/apollo 的新手,但我看不出哪里出错了。

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;
};

模型在我的 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);
    },
  },
};