【问题标题】:Two Knex queries (node.js) and one of it - in forEach loop两个 Knex 查询(node.js)和其中一个 - 在 forEach 循环中
【发布时间】:2022-06-11 00:48:56
【问题描述】:

一个表是 UserChats,其中包含与用户聊天的列表。 另一个表是包含所有聊天的 ChatList。

我需要将特定用户的聊天数组构建到变量中并返回。

_DB("UserChats").select('*').where({
 
  uID: user_id
 
}).then(chats => {
 
  const userChats = []
 
  chats.forEach(chat => {
 
    _DB('ChatList').where({
 
      id: chat.chatID
 
    }).select('*').then(chat_data => {
 
      userChats.push(chat_data);
 
    });
 
  });

 return userChats; // but this variable is empty

});

如何优雅地重写代码,让所有代码都被执行?

连接查询如下:

_DB('UserChats')
.select('*')
.where({ "UserChats.uID": user_id })
.join('ChatList', 'UserChats.chatID', 'ChatList.id')
.then(function(rows) {
  return rows;
});

【问题讨论】:

  • 共享数据库结构,只是一个问题,你不能在表上应用连接吗?
  • @DhruvPal ChatList: id, chatName; UserChats:chatID、uID、roleID。不能使用join,因为我已经简化了逻辑模型,实际上我需要在每个forEach中多做一些动作。
  • 请用表格结构更新问题,你正在执行的操作是什么,我看不到。如果你添加这些,我可以有更好的可见性
  • @DhruvPal 在一张桌子上有一个聊天列表。另一个表存储有关哪些用户参与哪些聊天的数据。我们需要为特定用户进行选择,他参与的聊天并将所有这些定义在一个变量中。

标签: node.js select foreach knex.js


猜你喜欢
  • 2013-11-23
  • 1970-01-01
  • 1970-01-01
  • 2013-11-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多