I have four tables: Users, Orders, OrderProducts (join table), and Products.
I want to calculate totalprice column in Orders table. OrderProducts has quantity and productId, Products has price column.
Do I need to add price column in OrderProducts table for each item (price * quantity)?
You don't necessarily need to add a price column in the OrderProducts table. You can achieve this by creating a Sequelize association between the tables and using Sequelize's aggregation functions.
Now, you can calculate the total price dynamically during queries based on the associated data by using the Sequelize's SUM function to multiply the quantity from OrderProducts with the price from Products, resulting in the total price for each order :
It is equivalent to executing the following SQL querie:
This approach ensures that the totalPrice column in the Orders table stays up-to-date without the need for redundant data storage.