How can I count inside nested associations in Sequelize?

theNu :

I try to count product reviews in nested associations. With the following query.

const user = await User.findOne({
  where: {
    id: req.query.user
  },
  attributes: ["id", "name"],
  include: [
    {
      model: Category,
      as: "interests",
      attributes: ["category_name"],
      through: {
        attributes: []
      },
      include: [
        {
          model: Product,
          as: "products",
          attributes: {
            include: [
              [
                // How to count product_reviews here?
                sequelize.literal(`
                (SELECT COUNT(*) FROM product_reviews WHERE productId = Product.id)
                `),
                "num_reviews"
              ]
            ] 
          },
          include: [
            {
              model: User,
              as: "userReviews",
              attributes: []
            }
          ]
        }
      ]
    }
  ]
});

In the model definitions I have a belongsTo/haveMany association set up e.g.:

Inside my models

// User model
User.belongsToMany(models.Category, {
  through: "user_categories",
  as: "interests",
  foreignKey: "userId"
});
User.belongsToMany(models.Product, {
  through: "user_reviews",
  as: "reviews",
  foreignKey: "userId"
});

// Category model
Category.hasMany(models.Product, {
  foreignKey: "categoryId",
  as: "products"
});

// Product model
Product.belongsToMany(models.User, {
  through: "product_reviews",
  as: "userReviews",
  foreignKey: "productId"
});

// Product_reviews model
product_review.belongsTo(models.User, { foreignKey: "userId" });
product_review.belongsTo(models.Product, { foreignKey: "productId" });

How to count product reviews? Here the result I want.

{
  "id": 1,
  "name": "John Doe",
  "interests": [
    {
      "category_name": "Toys",
      "products": [
        {
          "id": 1,
          "name": "Lorem Ipsum",
          "num_reviews": 20 // I need to count # of reviews here
        },
        ...
      ]
    }
  ]
}

Can anyone explain how to get counting inside nested associated in this case?

Soham Lawar :

I guess you are on the right track and you just need to modify the way of constructing Sequelize literal for reviews count as follows -

sequelize.literal(`
                (SELECT COUNT(*) FROM product_reviews WHERE productId = \`products\`.\`id\`)
                `)

I hope it helps!

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=5679&siteId=1