问题描述
我有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_id
和merchant_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].dataValues
。CustomerMerchant
数据位于result2[0].dataValues.customers[0].CustomerMerchant