我有一个具有以下关系的用户实体:
User.associate = (models) => {
User.belongsToMany(User, {
as: "friends",
through: "user_friend",
onDelete: "CASCADE",
})
User.hasMany(models.Message, { as: "sentMessages", foreignKey: "senderId" })
User.hasMany(models.Message, {
as: "receivedMessages",
foreignKey: "recipientId",
})
}
和具有关系的消息实体:
Message.associate = (models) => {
Message.belongsTo(models.User, { foreignKey: "senderId" })
Message.belongsTo(models.User, { foreignKey: "recipientId" })
}
并且我正在尝试执行以下操作:get me a user, include their friends, include their conversation history with each friend
使用以下内容:
let user = await User.findOne({
where: {
auth_key: auth_key,
},
include: {
association: "friends",
attributes: ["first_name", "last_name", "chat_name", "profile_picture"],
through: {
attributes: [],
},
include: [
{
required: false,
association: "sentMessages",
where: {
recipientId: 1,
},
},
{
required: false,
association: "receivedMessages",
where: {
senderId: 1,
},
},
],
},
})
这确实可以完成工作,但看起来确实很混乱,我不希望将消息分为sent
和received
,我只是希望将它们组合在一起。当前响应如下:
{
"id": 1,
"username": "ajsmith",
"first_name": "Anthony",
"last_name": "Smith",
"chat_name": "Anthony.Smith",
"email": "[email protected]",
"createdAt": "2020-06-15T19:59:58.000Z",
"updatedAt": "2020-06-15T19:59:58.000Z",
"friends": [
{
"first_name": "Sarah",
"last_name": "Smith",
"chat_name": "Sarah.Smith",
"sentMessages": [
{
"id": 2,
"senderId": 2,
"recipientId": 1,
"type": "text",
"content": "Hi",
"createdAt": "2020-06-15T19:59:58.000Z",
"updatedAt": "2020-06-15T19:59:58.000Z"
}
],
"receivedMessages": [
{
"id": 1,
"senderId": 1,
"recipientId": 2,
"type": "text",
"content": "Hello",
"createdAt": "2020-06-15T19:59:58.000Z",
"updatedAt": "2020-06-15T19:59:58.000Z"
}
]
}
]
}
我不确定我的关系是否错误,查询是否错误或无法执行,但在过去一周中,我搜索了续集文档,stackoverflow及其之间的所有内容,但未找到解决方案。好像我可以在正在发生的OR
上包含LEFT OUTER JOIN
语句,那么我的消息可以包括已发送和已接收的消息,其中senderId或receiveId是我的用户。
如果您要混合使用Message关联,则不会使用关联本身,而是使用它们共享的内容-对Message进行建模。我会尝试这样的事情(大多数嵌套包括):
include: [
model: models.Message,
order: [['createdAt', 'asc']],
required: false,
where: {
[Sequelize.Op.or]: [
{recipientId: 1},
{senderId: 1}
]
}
]