Performing a subtraction operation on two fields in Sequelize

I have formulated my query as follows...

{
    where: {
      id: event.pathParameters.picId
    },
    'include': [{
      'model': db.reputations,
      'where': {
        'type': 'V_UP'
      },
      'as': 'up_reputations',
      'required': false
    }, {
      'model': db.reputations,
      'where': {
        'type': 'V_DONW'
      },
      'as': 'down_reputations',
      'required': false
    }],
    'attributes': [
      'id',
      'title',
      'data',
      'createdAt',
      [db.Sequelize.fn('count', db.Sequelize.col('up_reputations.type')), 'upVotes'],
      [db.Sequelize.fn('count', db.Sequelize.col('down_reputations.type')), 'downVotes']
    ]
}

What I am missing is an additional attribute called score, which should be calculated as upVotes minus downVotes. However, I am unsure how to accomplish this.

Answer №1

Here is a potential solution:

'attributes': [
      'id',
      'name',
      'info',
      'createdDate',
      [db.Sequelize.fn('sum', db.Sequelize.col('up_ratings.type')), 'totalUpVotes'],
      [db.Sequelize.fn('sum', db.Sequelize.col('down_ratings.type')), 'totalDownVotes'],
      [db.Sequelize.literal('(totalUpVotes - totalDownVotes)'), 'overallScore']
 ]

Answer №2

Experiment

[db.Sequelize.literal('SUM(`up_votes.count`) - SUM(`down_votes.count`)'), 'total']

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Switching Nested Table Columns - HTML, jQuery Skills

My experience with jQuery is still growing, but I'm well-versed in HTML and CSS. Currently, I am tasked with developing a new report featuring a nested table displaying quarterly results. You can view a sample of the Quarterly Report here. When a use ...

Adjust the CSS content using the data-content attribute to include line breaks

My current coding setup includes: <div id="mydiv" data-content="Loading..."></div> This is how I style it with CSS: #mydiv:after{ content: attr(data-content); height: 100%; opacity: 1; position: absolute; text-align: center; ...

How can I modify the default color in Google Charts Geomap?

I'm looking to customize the chart region color to a specific shade instead of the default yellow. Currently, I have only been able to change the marker color using the provided code to generate the chart data: dataTable = new google.visuali ...

What is the best way to create a basic accordion using only certain table rows?

I am faced with the task of transforming a HTML table that lists various items. Each <tr> within the table contains a unique title element, but there are cases where rows can share the same title indicating their relation. My goal is to implement jQu ...

I am attempting to assign a default value to a TextField by retrieving data from a GetMapping call in React, however, the value is not being successfully set

I am facing an issue with setting a default value for a TextField in my code. Even though I am trying to populate it with data from a GetMapping call, the value is not being set as expected. Here is the JSON response I receive from the API call: { "id": 1 ...

Make sure to transfer any data retrieved from a click event using JavaScript into a different field

Recently I delved into learning JavaScript and stumbled upon a coding problem that has me stumped! I'm looking for a way to display information in the blue area after selecting an option, showing details like the name of the food item and its price. ...

Angular components are not receiving the Tailwind CSS attributes applied to :root classes

In my Angular 12 project, I have integrated Tailwind CSS. The structure of the package.json is as below: { "name": "some-angular-app", "version": "0.0.0", "scripts": { "ng": "ng&quo ...

Navigate horizontally to specific points and restrict vertical movement

I'm using a fixed arrow-navigation feature that enables users to scroll left or right through multiple columns using jQuery with horizontally positioned anchors: $('html,body').animate({ scrollLeft: $(target).offset().left ...

eliminate currency match regular expression

Currently, I've implemented this regular expression to validate dollar amount inputs. parsley-regexp="^\$?[0-9][0-9\,]*(\.\d{1,2})?$|^\$?[\.]([\d][\d]?)$" I am now looking to modify the validation so that onl ...

Why won't my Chrome content script load even though I have the correct syntax and have tried troubleshooting?

I'm facing an issue with my extension where the file content.js is not being loaded on any webpage despite trying multiple troubleshooting steps. I've tried different permissions, changing site patterns, reinstalling, restarting Chrome, adjusting ...

Angular view fails to update after form submission when using ngDialog to change the scope

After starting my Angular journey, I decided to challenge myself by creating a comprehensive todo app for educational purposes. I seem to be missing something pretty basic, although I can't quite put my finger on it. It seems like there might be an is ...

Refine Your Search Findings

I have a code snippet that enables searching items from a dropdown menu with a search bar, but now I want to remove the dropdown and only keep the search functionality. How can I modify the code to separate the select feature from the independent search ...

launch a website independently of the original source code

I recently completed a website project using PHP. I'm interested in deploying it without sharing the source code. Is this something that can be done with PHP? Is there a way to convert my website's code into an intermediate form before deploymen ...

JavaScript loading screen with media query support

I'm currently working on a JavaScript splash screen that features a video background. When the user clicks on the screen, it should smoothly transition to the home page. However, for mobile devices, I want to display an image instead of the video. My ...

Issue with variable not being refreshed within requestJS's data event

I have been attempting to store the response from a URL in a variable for caching purposes and then send it upon subsequent requests. I am currently writing to the variable during the data event of the request. The variable does get updated, but I am encou ...

Grab a hold of the currently active controller in Angular

Is it possible to access a reference to the current instance of the controller from within its definition? My goal is to use `$compile` to create a modal and have it bound to the same controller that initiated its creation. Below is an example of what I w ...

Mapping geographic coordinates with a null projection using D3

With d3.geo.path having a null projection due to TopoJSON already being projected, it can be displayed without any additional transformation. My goal is to plot data in the format of [longitude, latitude] on a map. Here is a simplified version of my code: ...

Sliding and stacking div elements using JavaScript

I'm currently working on my website and encountered a slight obstacle. This is how my code looks at the moment. My goal is to position the "About" box beneath the "Home" box, and have the upper box slide down with the description when you click on the ...

Using AJAX to call a VB ASP.NET web method with parameters in the GET request

I've come across numerous inquiries regarding this issue, but I can't seem to find a solution (the abundance of questions on the internet about this topic is astonishing!!). Let me be direct: test.asmx 'Simple POST method with parameters ...

Struggling to make a variable pass in an Ajax post script

Having trouble passing the "filename" variable from main.php to save_sign.php. Can anyone provide assistance? main.php <? $filename="222222"; ?> <script> $(document).ready(function() { $('#signArea').signat ...