将一个Sequelize模型链接到另一个模型中的两个不同字段

时间:2017-06-19 12:59:18

标签: javascript mysql node.js relational-database sequelize.js

我有两种模式:

  • BusinessEntity
  • Invoice

我希望Invoicesellerbuyer,两者都指向BusinessEntity条记录。因此,我希望在invoices表格(Invoice模型)中包含两个字段:seller_idbuyer_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_idbuyer_id列。为什么呢?

我已成功插入发票,从business_entities表格中分配ID。

如果我想Invoice输出includeseller,我应该如何查询buyer

我试过了:

 Invoice.findOne({ include: [BusinessEntity] })

但是这个错误就失败了:

 business_entity is not associated to invoice!

正确的方法是什么?如何解决问题?

1 个答案:

答案 0 :(得分:4)

当您执行findOne查询时:Invoice.findOne({ include: [BusinessEntity] })同样重要的是提及别名。

因此,您需要的查询具有以下格式:

Invoice.findOne({
  include: [
    // Include the seller
    { model: BusinessEntity, as: 'seller' },
    // ...and the buyer
    { model: BusinessEntity, as: 'buyer' }
  ]
})