我有两种模式:
BusinessEntity
和Invoice
我希望Invoice
有seller
和buyer
,两者都指向BusinessEntity
条记录。因此,我希望在invoices
表格(Invoice
模型)中包含两个字段:seller_id
和buyer_id
。
所以,我做了这样的事情:
的BusinessEntity
const BusinessEntity = sequelize.define("business_entity", {
display_name: Sequelize.STRING
});
的 Invoice
const Invoice = sequelize.define("invoice", {
series: Sequelize.STRING,
number: Sequelize.INTEGER,
...
});
// Indeed, this creates the seller_id and buyer_id fields in the invoice
Invoice.belongsTo(BusinessEntity, { as: "seller" });
Invoice.belongsTo(BusinessEntity, { as: "buyer" });
我打电话给Invoice.belongsTo(BusinessEntity)
似乎并不自然,但如果我这样做:
BusinessEntity.belongsTo(Invoice, { as: "seller" });
BusinessEntity.belongsTo(Invoice, { as: "buyer" });
...根本不会创建seller_id
和buyer_id
列。为什么呢?
我已成功插入发票,从business_entities
表格中分配ID。
如果我想Invoice
输出include
和seller
,我应该如何查询buyer
?
我试过了:
Invoice.findOne({ include: [BusinessEntity] })
但是这个错误就失败了:
business_entity is not associated to invoice!
正确的方法是什么?如何解决问题?
答案 0 :(得分:4)
当您执行findOne查询时:Invoice.findOne({ include: [BusinessEntity] })
同样重要的是提及别名。
因此,您需要的查询具有以下格式:
Invoice.findOne({
include: [
// Include the seller
{ model: BusinessEntity, as: 'seller' },
// ...and the buyer
{ model: BusinessEntity, as: 'buyer' }
]
})