DEV Community

devspectre
devspectre

Posted on

Help me on Sequelize ORM

Hi!

I am new to Sequelize ORM so I am struggling to get through it.
I want to get a list of items and count of associated items by applying filter.
Here are my models

const ActionModel = db.define(
  'action',
  {
    id: {
      type: Sequelize.INTEGER,
      primaryKey: true,
      autoIncrement: true,
    },
    ...
    buttonIndex: { type: Sequelize.INTEGER },
    ...
  },
  {
    tableName: 'action',
  },
)


const PageModel = db.define(
  'pages',
  {
    id: {
      type: Sequelize.INTEGER,
      primaryKey: true,
      autoIncrement: true,
    },
    pageTitle: { type: Sequelize.INTEGER },
    pageLink: { type: Sequelize.STRING },
  },
  {
    tableName: 'pages',
  },
)

PageModel.hasMany(Action, { as: 'actions', onDelete: 'CASCADE'})
Enter fullscreen mode Exit fullscreen mode

So If I get a list of pages, it will look like this

[
    {
        "id": 1,
        "pageTitle": "Python community",
        "pageLink": "https://fairy-dev.io/python",
    }
]
Enter fullscreen mode Exit fullscreen mode

The actions are associated with pages as they happen on the pages.
I want to add two more fields to the response.
visitCount and buttonClickCount
visitCount is total number of actions on the page where buttonIndex == 0
buttonClickCount is total number of actions on the page where buttonIndex != 0

So the result will look like this

[
    {
        "id": 1,
        "pageTitle": "Python community",
        "pageLink": "https://fairy-dev.io/python",
        "visitCount": 5,
        "buttonClickCount": 24
    },
   {
        "id": 2,
        "pageTitle": "Sequelize community",
        "pageLink": "https://fairy-dev.io/sequelize",
        "visitCount": 7,
        "buttonClickCount": 57
    }
]
Enter fullscreen mode Exit fullscreen mode

I know I should use attributes and include but not sure what the exact answer is.
Any help would be appreciated.

Thanks in advance.

Top comments (0)