0

my use case is something like this,

  1. Users can review the dishes.
  2. Each review is stored in a table called ratings.
  3. When a new record inserted to the ratings table, Dish tables overall rating column should be updated with the average rating value.

I go though the docs and some questions in the stack-overflow and GitHub also. What I have done so far is.

const db = require("../models");
const Sequelize = require('sequelize');

export async function create(req, res, next) {
    try {
        const body = req.swagger.params.body.value;
        const rate = await db.ratings.create(body, {
            fields: ['user_id', 'dish', 'overall', 'notes', 'createdAt', 'updatedAt']
        })

        const average = await Sequelize.fn('AVG', Sequelize.col('overall'))
        res.sendStatus(200);
    } catch (error) {
        console.log(error);
        res.status(500).json(error)
    }
}

I think average function is

Sequelize.fn('AVG', Sequelize.col('overall'))

But I don't know how to call it on the model ratings

1 Answer 1

2

This is how you can use with attributes :

db.ratings.findAll({
    attributes : [ [Sequelize.fn('AVG', Sequelize.col('overall')),'overall'] ] // <--- All you need is this
}).then(data => {
    console.log(data);
})

For more detail : DO READ

Sign up to request clarification or add additional context in comments.

3 Comments

First things first, thanks a lot for continuously helping me to improve. =) I have changed my query to this const average = await db.ratings.findAll({ where:{ dish:1 }, attributes: [sequelize.fn('AVG', sequelize.col('overall'))] }) then the executed query was this SELECT AVG(overall) FROM ratings AS ratings WHERE ratings.dish = 1; But I haven't get anyoutput. I got only an empty object. But I copy the excuted query and run on the phpmyadmin then query excuted and gives me the output.
What could went wrong here? "findAll" will gives all the columns and pass the "attributes" will provide only mentioned columns. So I didn't mention any column is it the reason here?
@PathumSamararathna , have updated the answer , please try that one

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.