I have a Cart model with product_price and quantity. I am writing a sequelize query to calculate the total as price * quantity Here's my query
db.Cart.findAll({
attributes: {include: [[db.sequelize.condition(db.sequelize.col('cart_quantity'), '*', db.sequelize.col('price')),'tot']]}
})
Sequelize documentatoin says to access the value of 'tot' we use instance.get('tot'). So in the results console.log(item.get('tot') displays correct value
.then(function(dbCart) { //We have access to the products as an argument inside of the callback function
dbCart.forEach(function(item){
console.log(item.get('tot'));
});
var hbsObject = {
products: dbCart,
};
res.render("shop/cart", hbsObject);
});
});
Now when I try to access the value in my carts.handlebars file I am unable to display or access the value of 'tot' {{# each products }} {{tot}} or {{Cart.tot}} or {{products.tot}} or {{products.get('tot')}} yields no value {{/each}} How do I access and display the value of 'tot' in handlebars? Thank you
Try:
{{#each users}}
{{#dataValues}}
<p>Username: {{username}}</p>
<p>Email: {{email}}</p>
{{/dataValues}}
{{/each}}
Or try:
{{#each users}}
<p>Username: {{this.dataValues.username}}</p>
<p>Email: {{this.dataValues.email}}</p>
{{/each}}
As far as I can tell you can only access the result of the query with item.get('tot'), but since you can't call functions from handlebars you need a work around. One way to do it is to add a handlebars helper that just wraps the .get() function.
const Handlebars = require('handlebars');
Handlebars.registerHelper('sequelizeGet', function(obj, col) {
return obj.get(col);
});
And in the handlebars template access that helper like:
<span>{{sequelizeGet item 'tot'}}</span>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With