Ionică Bizău
Ionică Bizău

Reputation: 113345

Linking one Sequelize model to two different fields from another model

I have two models:

I want the Invoice to have a seller and a buyer, both pointing to BusinessEntity records. So, I expect to have in the invoices table (the Invoice model) two fields: seller_id and buyer_id.

So, I did something like this:

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" });

It doesn't seem natural to me to call Invoice.belongsTo(BusinessEntity), but if I do:

BusinessEntity.belongsTo(Invoice, { as: "seller" });
BusinessEntity.belongsTo(Invoice, { as: "buyer" });

...the seller_id and buyer_id columns are not created at all. Why?


I inserted successfully an invoice, assiging ids from the business_entities table.

How am I supposed to query the Invoice when I want to include the seller and the buyer in the output?

I tried:

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

But that fails with this error:

 business_entity is not associated to invoice!

What's the right way to do this? How to solve the problem?

Upvotes: 2

Views: 1360

Answers (1)

Emanuela Colta
Emanuela Colta

Reputation: 2207

When you are performing the findOne query: Invoice.findOne({ include: [BusinessEntity] }) it is important to mention the alias, also.

So, the query you need has this format:

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

Upvotes: 4

Related Questions