Sequelize包含关联将不起作用(GraphQL)

时间:2019-10-10 16:46:58

标签: node.js graphql sequelize.js apollo-server

我有两个模型UserFriendRequestUser可以有多个FriendRequests,并且FriendRequest属于User。当我尝试User.findOne并包含FriendRequest时,我得到

{
  ...
  FriendRequest: null
}

models / User.js

  const User = sequelize.define(
    "User",
    {
      ...
    },
    {
      tableName: "users"
    }
  );
  User.associate = function(models) {
    // associations can be defined here
    User.hasMany(models.FriendRequest);
  };

models / FriendRequest.js

"use strict";
module.exports = (sequelize, DataTypes) => {
  const FriendRequest = sequelize.define(
    "FriendRequest",
    {
      senderId: DataTypes.INTEGER,
      receiverId: DataTypes.INTEGER,
      status: DataTypes.INTEGER,
      UserId: DataTypes.INTEGER
    },
    {
      tableName: "friend_requests"
    }
  );
  FriendRequest.associate = function(models) {
    FriendRequest.belongsTo(models.User);
    // associations can be defined here
  };
  return FriendRequest;
};

graphql-modules / user.js

  type User {
    ...
    FriendRequest: [FriendRequest]
  }

graphql-modules / friend_request.js

  type FriendRequest {
    id: Int!
    senderId: Int!
    receiverId: Int!
    status: Int!
    UserId: Int!
  }

services / users_service.js

let searchUser = async (args) => {
  try {
    let user = await User.findOne({
        where: args,
        include: [
          {
            model: FriendRequest
          }
        ]
      });
      let request = await FriendRequest.findAll({ where: { UserId: args.id } });
      console.log(request);
    return user;
  } catch (err) {
    throw new Error(err);
  }
};

上面,我添加了请求变量,以查看是否可以查询FriendRequest,是的,我得到了正确的结果。

我也想做

include: [
          {
            model: FriendRequest,
            where: {UserId: args.id}
          }
        ]

但是它返回user = null;

我需要用户变量来返回FriendRequests数组。 这些行存在于数据库中: ID senderId接收者ID状态UserId 7 5 2 0 5

1 个答案:

答案 0 :(得分:1)

有同样的问题,问题是Sequelize生成关联的复数名称并保留首字母大写,因此为了解决这个问题,我为关联使用了别名。

// models/User.js
User.hasMany(models.FriendRequest, {
  as: 'friendRequests'
});

// graphql-modules/user.js
type User {
  ...
  friendRequests: [FriendRequest]
}

// services/users_service.js
User.findOne({
  where: args,
  include: [
    {
      model: FriendRequest,
      as: 'friendRequests'
    }
  ]
});