I have two models User
and FriendRequest
. User
can have many FriendRequests
and FriendRequest
belongs to User
. When I try to User.findOne
and include FriendRequest
I get
{
...
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);
}
};
Above, I added the request variable to see if I can query FriendRequest and yes I got the correct results.
I also tried to do
include: [
{
model: FriendRequest,
where: {UserId: args.id}
}
]
But it returns user=null;
I need the user variable to return an array of FriendRequests. The rows exist on the database: Id senderId receiverId status UserId 7 5 2 0 5
Had the same issue, the problem is that Sequelize generates the plural name of the association keeping the first letter capital, so to solve it I used an alias for the association.
// 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'
}
]
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.