【发布时间】:2021-01-27 03:36:12
【问题描述】:
我试图根据用户 ID 组合 textContent 数组进行聊天对话,但退出结果不是我要寻找的,来自@Barman 答案而不是 sender_user ID 必须是“用户”表中用户的 ID,检查我的代码示例。我是新手,任何帮助将不胜感激。谢谢!
这就是我想要达到的目标:
contacts: [
{
id: 1
},
{
id: 2
}
],
"chats": {
userid-> "1": {
"isPinned": "true",
"msg": [
{
"textContent": "Hello",
"time": "2020-10-07T15:04:40.000Z",
"isSent": "true",
"isSeen": "true"
},
{
"textContent": "Hello to you, john!",
"time": "2020-10-07T15:04:40.000Z",
"isSent": "true",
"isSeen": "true"
}
]
},
"2": {
"isPinned": "true",
"msg": [
{
"textContent": "how are you?",
"time": "2020-10-07T15:04:40.000Z",
"isSent": "true",
"isSeen": "true"
},
{
"textContent": "im fine thx you?",
"time": "2020-10-07T15:04:40.000Z",
"isSent": "true",
"isSeen": "true"
}
]
}
}
基于我的退出代码的结果是这样的,id "1":{ 和 "2" 必须来自 getContacts 用户 ID,而不是来自 sender_userid:
{
"chats": {
"1": {
"isPinned": "false",
"msg": [
{
"textContent": "Hello",
"time": "Mon Dec 10 2018 07:45:00 GMT+0000 (GMT)",
"isSent": "true",
"isSeen": "true"
},
{
"textContent": "im fine thx you?",
"time": "Mon Dec 10 2018 07:45:23 GMT+0000 (GMT)",
"isSent": "true",
"isSeen": "true"
}
]
},
"2": {
"isPinned": "false",
"msg": [
{
"textContent": "How are you?",
"time": "Mon Dec 10 2018 07:45:00 GMT+0000 (GMT)",
"isSent": "true",
"isSeen": "true"
},
{
"textContent": "Hello to you, john!",
"time": "Mon Dec 10 2018 08:45:00 GMT+0000 (GMT)",
"isSent": "true",
"isSeen": "true"
}
]
}
Mysql 聊天和用户表:
js代码:
getContacts: (q, callBack) => {
pool.query(
'SELECT u.* FROM `users` u INNER JOIN `my_friends` f ON f.myid = u.id WHERE f.friend_id = ? AND f.status = ?',
[q, 1],
(error, contacts) => {
if (error) {
callBack(error)
}
return callBack(null, contacts)
}
)
},
getChats: callBack => {
pool.query(
'SELECT * FROM chat WHERE reciever_userid=1 AND sender_userid=5 OR sender_userid=1 AND reciever_userid=5 ORDER BY time', [],
(error, chats) => {
if (error) {
callBack(error)
}
return callBack(null, chats)
}
)
}
getChats((err, chatz) => {
if (err) {
console.log(err)
return
}
getChats: (req, res) => {
getContacts((err, users) => {
getChats((err, chatz) => {
if (err) {
console.log(err)
return
}
const chats = {}
chatz.forEach(({sender_userid, isPinned, textContent, time, isSent, isSeen}) => {
if (chats[sender_userid]) {
chats[sender_userid].msg.push({
textContent,
time,
isSent,
isSeen
})
} else {
chats[sender_userid] = {
isPinned,
msg: [
{
textContent,
time,
isSent,
isSeen
}
]
}
}
})
return res.json({
chats
})
})
})
}
}
【问题讨论】:
-
如果您只是要删除大部分元素,为什么还要使用
SELECT *?只需选择您想要的列。 -
如果我这样做,输出会被搞砸......谢谢回复,你能帮帮我吗?
标签: mysql node.js arrays json nested