问题描述
我试图让每个用户的对话显示在我前端的收件箱屏幕上.我能够将消息发布到数据库,但是当我尝试获取它们时,我不断收到
[SequelizeEagerLoadingError]:消息与对话无关!
谁能看看我的代码.
这是我的获取请求:
router.get('/', auth, (req, res) => {对话.findAll({在哪里: {[操作]:[{user1: { [Op.eq]: req.user.id },user2: { [Op.eq]: req.user.id },},],},包括:[{模型:消息}],}).then(() => res.send()).catch((err) => console.log(err));});
这是我的对话模型
const Conversation = db.define('Conversation', {});module.exports = 对话;Conversation.associate =(模型)=>{Conversation.hasMany(models.Message, {外键:'conversationId',});Conversation.belongsTo(models.Post, {外键:'PostId',});};User.hasMany(对话,{外键:'user1',});User.hasMany(对话,{外键:'user2',});
这是我的消息模型:
const Message = db.define('Message', {ID: {主键:真,类型:Sequelize.INTEGER,},发件人ID: {类型:Sequelize.STRING,},接收者 ID:{类型:Sequelize.STRING,},信息: {类型:Sequelize.STRING,},对话 ID:{类型:Sequelize.INTEGER,},});module.exports = 消息;User.hasMany(消息,{外键:'senderId',如:'已发送消息',});User.hasMany(消息,{外键:'receiverId',如:'ReceivedMessage',});Message.associate =(模型)=>{Message.belongsTo(models.User, {外键:'senderId',如:发件人",});Message.belongsTo(models.User, {外键:'receiverId',如:'接收器',});Message.belongsTo(models.Conversation, {外键:'conversationId',});};Post.hasMany(Conversation, { foreignKey: 'PostId' });
更新
删除后
Conversation.hasMany(models.Message,{foreginKey:"conversationId"})
从我的对话模型中的关联方法并将其添加到我的消息模型中,我不再收到关联错误,但是现在当我尝试测试 get 请求时,当我的数据库充满条目时,我不断收到空响应.
>这是我更新的获取请求:
router.get('/',auth,async(req,res)=>{const 对话 = 等待 Conversations.findAll({包括:[{型号:消息,要求:假,}],在哪里:{[操作]:[{user1:{[Op.eq]:req.user.id},user2:{[Op.eq]:req.user.id},}]},});if(!conversation) return res.send().catch(err=>console.log(err))res.status(200).send()})
这是我在终端的回复:
正在执行(默认):SELECT "Conversation"."id",Conversation".createdAt"、Conversation".updatedAt"、对话".用户1",对话".用户2",Conversation".PostId"、Messages".id"ASMessages.id",消息".senderId"ASMessages.senderId",消息".接收者ID"作为Messages.receiverId",消息".消息"ASMessages.message",消息".conversationId"ASMessages.conversationId",消息".createdAt"ASMessages.createdAt",消息".updatedAt"ASMessages.updatedAt"来自对话"AS对话"左外加入消息"AS消息"ON Conversation".id"=消息".conversationId"WHERE ((Conversation".user1"= 43 AND对话".user2"= 43));
在尝试解决这个问题很多天之后,在 Anatoly 和 doublesharp 的帮助下,我终于找到了方法.
我的问题是我的对话模型中的关联方法由于某种原因没有被执行,我仍然不知道,所以我从对话模型中的关联方法中删除了它并将其添加到我的消息模型中并且它起作用了.
这是我的代码:
消息模型:
const Message = db.define("Message", {发件人ID: {类型:Sequelize.STRING,},接收者 ID:{类型:Sequelize.STRING,},信息: {类型:Sequelize.STRING,},对话ID:{类型:Sequelize.INTEGER,}});module.exports = 消息;User.hasMany(消息,{如:已发送消息",外键:'senderId',});User.hasMany(消息,{如:ReceivedMessage",外键:'receiverId',});Message.associate =(模型)=>{Message.belongsTo(models.User, {如:发件人",外键:senderId",allowNull: 假});Message.belongsTo(models.User, {如:接收者",外键:receiverId",allowNull: 假});Message.belongsTo(models.Conversations, { allowNull: false },{外键:conversationId",}};Conversation.hasMany(消息,{外键:conversationId",});
这是我的对话模型:
const Conversation = db.define(Conversation", {});module.exports = 对话;User.hasMany(对话,{外键:'user1'});User.hasMany(对话,{外键:'user2'});Conversation.belongsTo(User, { as: 'Creator', foreignKey: 'user1', allowNull:错误的 })Conversation.belongsTo(User, { as: 'Recipient', foreignKey: 'user2',allowNull: 假 })
这是我的后期模特关联:
Post.hasMany(Conversation, { foreignKey: "PostId" });Conversation.belongsTo(发布,{外键:PostId",allowNull: 假})
这是我的 GET 请求:
router.get('/', auth, async (req, res) => {尝试 {const 对话 = 等待 Conversation.findAll({包括: [{型号:消息,在哪里: {[操作]:[{ senderId: req.user.id },{receiverId: req.user.id },],},要求:真,//右加入}],});返回 res.json(对话);} 抓住(错误){控制台日志(错误);返回 res.status(500).send(err);}});
这是我的邮递员回复:
[{id":1,用户 1":43,用户 2":45,PostId":523,消息":[{id":1,senderId":43,receiverId":45,消息":我的第一条消息"对话》,conversationId":1,}]},{id":4,用户 1":43,用户 2":45,PostId":522,消息":[{id":7,senderId":43,receiverId":45,消息":再来一次",conversationId":4,},]},{id":5,用户 1":45,用户 2":43,PostId":518,消息":[{id":11,senderId":45,接收器 ID":43,消息":你好43",conversationId":5,}]}]I am trying to get the conversations of each user to show them on my inbox screen in my front-end. I am able to post messages to the database, but when I try to getting them, I keep getting
[SequelizeEagerLoadingError]: Message is not associated to Conversation!
Can someone please have a look at my code.
Here is my get request:
router.get('/', auth, (req, res) => {
Conversation.findAll({
where: {
[Op.or]: [
{
user1: { [Op.eq]: req.user.id },
user2: { [Op.eq]: req.user.id },
},
],
},
include: [{ model: Message }],
})
.then(() => res.send())
.catch((err) => console.log(err));
});
Here is my Conversation Model
const Conversation = db.define('Conversation', {
});
module.exports = Conversations;
Conversation.associate = (models) => {
Conversation.hasMany(models.Message, {
foreignKey: 'conversationId',
});
Conversation.belongsTo(models.Post, {
foreignKey: 'PostId',
});
};
User.hasMany(Conversation, {
foreignKey: 'user1',
});
User.hasMany(Conversation, {
foreignKey: 'user2',
});
Here is my Message model:
const Message = db.define('Message', {
id: {
primaryKey: true,
type: Sequelize.INTEGER,
},
senderId: {
type: Sequelize.STRING,
},
receiverId: {
type: Sequelize.STRING,
},
message: {
type: Sequelize.STRING,
},
conversationId: {
type: Sequelize.INTEGER,
},
});
module.exports = Message;
User.hasMany(Message, {
foreignKey: 'senderId',
as: 'SentMessage',
});
User.hasMany(Message, {
foreignKey: 'receiverId',
as: 'ReceivedMessage',
});
Message.associate = (models) => {
Message.belongsTo(models.User, {
foreignKey: 'senderId',
as: 'Sender',
});
Message.belongsTo(models.User, {
foreignKey: 'receiverId',
as: 'Receiver',
});
Message.belongsTo(models.Conversation, {
foreignKey: 'conversationId',
});
};
Post.hasMany(Conversation, { foreignKey: 'PostId' });
Update
After removing
Conversation.hasMany(models.Message,{foreginKey:"conversationId"})
from my associate method in my Conversation Model and adding it into my Message model i stopped getting the association error, but now when i try testing the get request i keep getting an empty response while my database is full of entries.
Here is my updated get request:
router.get('/',auth,async(req,res)=>{
const conversation = await Conversations.findAll({
include:[{
model:Message,
required: false,
}],
where:{
[Op.or]:[{
user1:{[Op.eq]:req.user.id},
user2:{[Op.eq]:req.user.id},
}]
},
});
if(!conversation) return res.send().catch(err=>console.log(err))
res.status(200).send()
})
Here is my response in the terminal:
Executing (default): SELECT "Conversation"."id",
"Conversation"."createdAt", "Conversation"."updatedAt",
"Conversation"."user1", "Conversation"."user2",
"Conversation"."PostId", "Messages"."id" AS "Messages.id",
"Messages"."senderId" AS "Messages.senderId",
"Messages"."receiverId" AS
"Messages.receiverId",
"Messages"."message" AS "Messages.message",
"Messages"."conversationId" AS "Messages.conversationId",
"Messages"."createdAt" AS "Messages.createdAt",
"Messages"."updatedAt" AS "Messages.updatedAt" FROM "Conversations"
AS "Conversation" LEFT OUTER
JOIN "Messages" AS "Messages" ON "Conversation"."id" =
"Messages"."conversationId" WHERE (("Conversation"."user1" = 43 AND
"Conversation"."user2" = 43));
after many days of trying to solve this problem and with the help of Anatoly and doublesharp and i finally figured out how.
My problem was my associate method inside my Conversation Model was not getting executed for some reason i still do not know, so i removed it from my associate method inside my conversation model and added it inside my messages model and it worked.
Here is my code:
Message Model:
const Message = db.define("Message", {
senderId: {
type: Sequelize.STRING,
},
receiverId: {
type: Sequelize.STRING,
},
message: {
type: Sequelize.STRING,
},
conversationId:{
type: Sequelize.INTEGER,
}
});
module.exports = Message;
User.hasMany(Message, {
as:"SentMessage",
foreignKey: 'senderId',
});
User.hasMany(Message, {
as:"ReceivedMessage",
foreignKey: 'receiverId',
});
Message.associate = (models) => {
Message.belongsTo(models.User, {
as:"Sender",
foreignKey: "senderId",
allowNull: false
});
Message.belongsTo(models.User, {
as:"Receiver",
foreignKey: "receiverId",
allowNull: false
});
Message.belongsTo(models.Conversations, { allowNull: false },{
foreignKey: "conversationId",
}
};
Conversation.hasMany(Message,{
foreignKey: "conversationId",
}
);
Here is my Conversation model:
const Conversation = db.define("Conversation", {});
module.exports = Conversation;
User.hasMany(Conversation, {
foreignKey: 'user1'
});
User.hasMany(Conversation, {
foreignKey: 'user2'
});
Conversation.belongsTo(User, { as: 'Creator', foreignKey: 'user1', allowNull:
false })
Conversation.belongsTo(User, { as: 'Recipient', foreignKey: 'user2',
allowNull: false })
Here is my Post Model associations:
Post.hasMany(Conversation, { foreignKey: "PostId" });
Conversation.belongsTo(Post,{
foreignKey: "PostId",
allowNull: false
})
Here is my GET request:
router.get('/', auth, async (req, res) => {
try {
const conversations = await Conversation.findAll({
include: [{
model: Message,
where: {
[Op.or]: [
{ senderId: req.user.id },
{ receiverId: req.user.id },
],
},
required: true, // RIGHT JOIN
}],
});
return res.json(conversations);
} catch (err) {
console.log(err);
return res.status(500).send(err);
}
});
Here is my Postman Response:
[
{
"id": 1,
"user1": 43,
"user2": 45,
"PostId": 523,
"Messages": [
{
"id": 1,
"senderId": 43,
"receiverId": 45,
"message": "My first message & Conversation",
"conversationId": 1,
}
]
},
{
"id": 4,
"user1": 43,
"user2": 45,
"PostId": 522,
"Messages": [
{
"id": 7,
"senderId": 43,
"receiverId": 45,
"message": "One more time",
"conversationId": 4,
},
]
},
{
"id": 5,
"user1": 45,
"user2": 43,
"PostId": 518,
"Messages": [
{
"id": 11,
"senderId": 45,
"receiverId": 43,
"message": "Hello 43",
"conversationId": 5,
}
]
}
]
这篇关于如何获取每个用户的对话并包含消息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!