Search code examples
node.jspostgresqlormsequelize.js

How to get associations in an array using sequelize findAll()?


I'm pretty new to Sequelize and trying to learn all of the cool tricks you can use to format your queries, but have run into a bit of a wall.

Basically I have a table "invoices". I have another table "invoice_items" which has a relationship many invoice_items to one invoice.

Currently I am trying to include this one to many association in a findAll query such that the invoice_items are nested in an array in each invoice object.

Something along the lines of:

[
  {
    name: invoice1
    invoiceItems: [
      itemOne,
      itemTwo,
    ]
  },
    {
    name: invoice2
    invoiceItems: [
      itemOne,
      itemTwo,
    ]
  }
]

The closest I can get is outputting multiple invoice objects (one for each association). Here is the query, which outputs the object below.

db.invoice.findAll({
    where: {
        userId: req.user.id
    },
    include: "invoiceItems",
    raw : true,
    nest : true
});
[
  {
    name: invoice1
    invoiceItems: itemOne
  },
  {
    name: invoice1
    invoiceItems: itemTwo
  },
  {
    name: invoice2
    invoiceItems: itemOne
  },
  {
    name: invoice2
    invoiceItems: itemTwo
  }
]

Is there anyway to achieve what I am hoping to achieve here? Thanks in advance!

Edit:

I was able to get the desired result by using get() to help process the result. The issue I have been having is raw: true seems to not work with eager loading.

Here is the processed option in case anyone finds it helpful.

db.invoice.findAll({
    where: {
        userId: req.user.id
    },
    include: "invoiceItems",
}).then(results => {
    let processedResults = [];
    for (result of results){
        processedResults.push(result.get({ plain: true }));
    }
    return processedResults;
});

Solution

  • I was able to get the desired result by using get() to help process the result. The issue I have been having is raw: true seems to not work with eager loading.

    Here is the processed option in case anyone finds it helpful.

    db.invoice.findAll({
        where: {
            userId: req.user.id
        },
        include: "invoiceItems",
    }).then(results => {
        let processedResults = [];
        for (result of results){
            processedResults.push(result.get({ plain: true }));
        }
        return processedResults;
    });