You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Sequelize中通过当前查询表的数据访问另一张关联表

你要实现Friends表关联查询另一张表(以下示例默认你要关联的是用户表Users,可替换为你实际的表名),按以下步骤操作即可:

步骤1:定义模型关联

在你初始化Sequelize模型的位置,添加Friends和目标表的关联关系,示例代码如下:

// 假设Friends表有两个字段:fid(当前用户id)、friend_id(好友的用户id),要关联Users表的id字段
database.Friends.belongsTo(database.Users, {
  foreignKey: 'friend_id', // 替换为Friends表里存储的对应用户表的id字段名
  as: 'friendInfo' // 关联数据的别名,可自定义
});

如果你的Friends表还有其他要关联的表,按照相同逻辑补充关联规则即可。

步骤2:修改查询方法加入关联配置

修改你现有的getFriends方法,在查询参数里加include配置,直接把关联表的数据一起查出来:

let getFriends = async (id) => {
  const project = await database.Friends.findAndCountAll({ 
    where: { fid: id },
    include: [{
      model: database.Users, // 替换为你要关联的表的模型
      as: 'friendInfo' // 和你刚才定义关联时的别名保持一致
    }]
  });
  return project.rows
}

查询返回的每条好友数据里,会自动带上friendInfo字段,存储对应关联表的所有数据。

步骤3:EJS页面直接调用即可

在ejs模板里直接访问关联字段就行,示例:

<% friends.forEach(friend => { %>
  <div>好友昵称:<%= friend.friendInfo.nickname %></div>
  <div>好友头像:<%= friend.friendInfo.avatar %></div>
<% }) %>

如果暂时不想配置模型关联,也可以在拿到Friends的查询结果后批量查询另一张表,不过性能远不如关联查询,不推荐生产环境使用:

let getFriends = async (id) => {
  const { rows } = await database.Friends.findAndCountAll({ where: { fid: id } });
  // 提取所有好友的id
  const friendIds = rows.map(item => item.friend_id);
  // 批量查询用户表
  const userInfos = await database.Users.findAll({ where: { id: friendIds } });
  // 把用户信息拼到好友数据里
  return rows.map(friend => {
    friend.friendInfo = userInfos.find(user => user.id === friend.friend_id);
    return friend;
  })
}

内容的提问来源于stack exchange,提问作者pinkpumpkinaid

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 07:15:05