如何使用Sequelize连接3个表?

人气:493 发布:2022-10-16 标签: node.js sequelize.js

问题描述

我有3个表名为:

    customers
columns are: id, customer_full_name

    transaction_details
columns are: id, customer_id, amount, merchant_id

    merchants
columns are: id, merchant_full_name

transaction_details表包含customer_idmerchant_id两个外键。 一个客户可能有多笔交易。一个商家也可能有多笔交易。

情况: 商家登录网站查看属于该商家的交易详情。我要显示的是一个包含以下列的表格:

a. Transaction ID
b. Customer Name
c. Transaction Amount

我的代码如下:

  Merchant.findAll({
      where: {
          id:req.session.userId,
      },
      include:[{
        model:TransactionDetails,
        required: false
      }]
    }).then(resultDetails => {
        var results = resultDetails;
});

我上面的代码没有给出我想要的结果。我如何修复此问题?

推荐答案

您需要的是belongsToMany关联,以防您尚未定义它。以下是示例

const Customer = sequelize.define('customer', {
  username: Sequelize.STRING,
});

const Merchant = sequelize.define('merchant', {
  username: Sequelize.STRING,
});
Customer.belongsToMany(Merchant, { through: 'CustomerMerchant' });
Merchant.belongsToMany(Customer, { through: 'CustomerMerchant' });

sequelize.sync({ force: true })
  .then(() => {
    Customer.create({
      username: 'customer1',
      merchants: {
        username: 'merchant1'
      },
    }, { include: [Merchant] }).then((result) => {
      Merchant.findAll({
        include: [{
          model: Customer
        }],
      }).then((result2) => {
        console.log('done', result2);


      })
    })
  });

现在result2具有所有值。Customer数据可在以下位置访问 result2[0].dataValues.customers[0].dataValuesCustomerMerchant数据位于result2[0].dataValues.customers[0].CustomerMerchant

657