Home > Enterprise >  Sequelize : Sum with include - TypeError: Cannot read properties of undefined (reading 'fn'
Sequelize : Sum with include - TypeError: Cannot read properties of undefined (reading 'fn'

Time:06-05

I would like to make a sum in query like in SQL :

SELECT `coproprietaires`.`id`,
       `coproprietaires`.`name`,
       `coproprietaires`.`email`,
       `LotsOwner`.`lotId` AS `lotId`,
       `LotsOwner`.`distributionKeyId` AS `costKey`,
       SUM(`LotsOwner`.`tantiemeNumber`) AS `tantiemeNumber`
FROM `coproprietaires` AS `coproprietaires`
LEFT OUTER JOIN `lotstantiemes` AS `LotsOwner` ON `coproprietaires`.`id` = `LotsOwner`.`ownerId`
WHERE `coproprietaires`.`coproNumber` = '85656913'
GROUP BY `name`,
         `LotsOwner`.`distributionKeyId`
ORDER BY `coproprietaires`.`name` ASC;

When I write it in Sequelize format , it doesn't work:

const data = await modelOwners.findAll({
  attributes: ["id", "name", "email"],
  include: [
    {
      model: modelLotsTantiemes,
      as: "LotsOwner",
      attributes: [
        "lotId",
        ["distributionKeyId", 'costKey'],
        [ sequelize.fn('sum', sequelize.col("tantiemeNumber")), 'totalTantieme' ],
      ],
    },
  ],
  where: { coproNumber: req.header("customerId") },
  group: ["name", "LotsOwner.distributionKeyId"],
  raw: true,
  order: [["name", "ASC"]],
});

And the error is :

TypeError: Cannot read properties of undefined (reading 'fn')

Somebody can help me ? please.

Thx

CodePudding user response:

You should call fn and col as a static members of Sequelize and as an instance members of sequelize (which stores a connection):

const Sequelize = require('sequelize')
...
[ Sequelize.fn('sum', Sequelize.col("tantiemeNumber")), 'totalTantieme' ]
  • Related