Does Sequelize include a 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 extracted?

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

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

For example, I would ideally want 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" } }; 

How to do it?

I am currently using Sequelize.query to run custom queries, but then I lose all the functions of Sequelize and review what Sequelize has already done. Another option that I have in mind is to run two queries - one completely through Sequelize for the underlying data, and the second only to get the calculated data, and then copy the calculated data into objects in JavaScript.

+8
source share
2 answers

What I ended up with was creating a view inside the database, and then defining seelize for the view, just like it was in the table, and included the computed field as it is part of the view.

This works great, but not perfect.

0
source share

Perhaps you can use getterMethods of the Sequelize define model:

 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... }, { getterMethods: { totalSales: function() { var pId = this.productId // here happened your subQuery: "SELECT SUM(OD.TotalPrice) FROM OrderDetails OD WHERE OD.productID = " + pId return something; } } }); 
0
source share

All Articles