如何使用Sequelize加入3个表?

时间:2018-05-31 14:47:50

标签: 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;
});

我上面的代码没有给出我想要的结果。我该如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

如果您尚未定义,则需要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个数据