我有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;
});
我上面的代码没有给出我想要的结果。我该如何解决这个问题?
答案 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].dataValues
。 CustomerMerchant
result2[0].dataValues.customers[0].CustomerMerchant
个数据