node.js - Sequelize : join three tables

标签 node.js postgresql sequelize.js

考虑这些表

const User = sequelize.define('users', {
  name: {
    type: Sequelize.TEXT
  },
  password: {
    type: Sequelize.TEXT
  },
  status: {
    type: Sequelize.BIGINT,
    field: 'statusId',
  },
  date_of_birth: {
    type: Sequelize.DATE
  },
});

const Status = sequelize.define('statuses', {
  name: {
    type: Sequelize.TEXT
  },
});


const UserRate = sequelize.define('user_rates', {
  title: {
    type: Sequelize.TEXT
  },
  user: {
    type: Sequelize.BIGINT,
    field: 'userId'
  },
  comment: {
    type: Sequelize.TEXT
  },
  rate: {
    type: Sequelize.NUMBER
  },
});


User.belongsTo(Statuses, { foreignKey: 'statusId', as: 'userStatus'})

User.hasMany(UserRate, { foreignKey: 'userId', as: 'userRate' })

UserRate.findAll({ include: ['userRate']});
查询运行良好,我明白了:
 {
       title: 'test',
       rate: 4,
       user: 1,
       comment: 'test',
       userRate: {
          name: 'test',
          password: 'test',
          status: '1',
          date_of_birth: '11/22/1111',
       }
    }
但如果我想得到这个:
{
       title: 'test',
       rate: 4,
       user: 1,
       comment: 'test',
       userRate: {
          name: 'test',
          password: 'test',
          status: '1',
          date_of_birth: '11/22/1111',
          userStatus: {
             name: 'active',
             id: 1,
          }
       }
    }
我想在用户对象中包含状态。我看了很多地方,但找不到解决方案。我什至试试这个:
UserRate.findAll({ include: ['userRate', 'userStatus]});
但这根本不起作用
我试图使用belongsToMany,但我无法让它工作,也许我不知何故做得不对。非常感谢任何帮助

最佳答案

UserRate 与 userStatus 没有任何直接关联/关系。所以你要把它包含在 User 模型中。

UserRate.findAll({
    include: [{
        model: User, as: 'userRate',
        include: [{
            model: Status, as: 'userStatus',
        }],
    }],
});
如果您是第一次看到这个,请不要对 include 中的对象数组感到困惑。您可以包含更多模型, 应该与包含它的父 定义关联/关系。

关于node.js - Sequelize : join three tables,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64618252/

相关文章:

postgresql - 如果表达式与存储在另一个表中的记录匹配,如何从一个表中选择匹配的记录,该表的字段包含 SQL 表达式

javascript - 同一路由上的多个 get 方法在 express 和 sequelize 中发生冲突

node.js - mocha,用于 nodejs 中的 post 的 chai 测试

node.js - Sequelize Association 获取像 JSON 这样的数据

javascript - Javascript fs.readFileSync 返回什么编码?

node.js - 如何使用 mongoose 添加 GeoJson 数据?

node.js - Electron中检测 Node 环境的方法

没有找到 jQuery。请确保在 SignalR 客户端 JavaScript 文件之前引用 jQuery

java - 如何检查 Java JDBC 代码是否使用了正确的列名?

sql - PostgreSQL 中的查询优化