我有两个模型User
和FriendRequest
。 User
可以有多个FriendRequests
,并且FriendRequest
属于User
。当我尝试User.findOne
并包含FriendRequest
时,我得到
{
...
FriendRequest: null
}
const User = sequelize.define(
"User",
{
...
},
{
tableName: "users"
}
);
User.associate = function(models) {
// associations can be defined here
User.hasMany(models.FriendRequest);
};
"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;
};
type User {
...
FriendRequest: [FriendRequest]
}
type FriendRequest {
id: Int!
senderId: Int!
receiverId: Int!
status: Int!
UserId: Int!
}
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
答案 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'
}
]
});