Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sequelize include calculated field that is calculated in the database?

Using Sequelize in Node.js is it possible to define a field that is calculated in the database when data is retrieved?

I understand I can add a custom getter to the DAO to calculate things in Node but that can only work on data already loaded.

My goal is to define a calculation that is run in the database and thus can use a subquery to calculate using other data.

For example, I'd ideally like to do this:

Products = Sequelize.define('Product', {
    'productId': { 
            type: Sequelize.INTEGER, 
            primaryKey: true, 
            autoIncrement: true 
        },
    'isProductActive': Sequelize.INTEGER,
    'productName': Sequelize.STRING,
    'productPrice': Sequelize.DECIMAL,


    // This is what I don't think Sequelize supports
    // but is what I ideally want to do...
    'totalSales': {
            type: Sequelize.DECIMAL,
            subQuery: "SELECT SUM(OD.TotalPrice) FROM OrderDetails OD WHERE OD.productID = Products.productID"
        }
};

Any way to do this?

For now I'm using Sequelize.query to run custom queries but then I lose all of the functionality of Sequelize and find myself redoing what Sequelize already done. Another option I've though of is to run two queries--one fully through Sequelize for basic data and a second just to get calculated data, and then copy the calculated data to the objects in JavaScript.

like image 609
Samuel Neff Avatar asked Oct 06 '14 02:10

Samuel Neff


1 Answers

What I ended up doing is creating a view inside the database and then a sequelize definition for the view, just like it was a table, and included the calculated field since it is a part of the view.

This worked fine but was not ideal.

like image 74
Samuel Neff Avatar answered Sep 19 '22 09:09

Samuel Neff