Using "array_agg" in a "having clause" with Sequelize

I am facing a particular scenario with my database setup. I have three tables named computers, flags, and computerFlags that establish relationships between them. The structure of the computerFlags table is as follows:

computerName | flagId
  computer1  | flag1
  computer1  | flag2
  computer2  | flag2
  computer2  | flag3

The computer3 entry does not have any flags associated with it, therefore it is not listed in the table. Using Sequelize, I am trying to create a query that will count all computers without the "flag3". In the example table above, the desired output would be 2 (for "computer1" and "computer3").

This is the current code snippet I have:

import { DataTypes, Sequelize, Op } from "sequelize";

(async () => {
    try {
        const postgresDB = new Sequelize('postgres://<my-pg-credentials>>', {
            logging: true,
        });

        const computers = postgresDB.define('computer', {
            name: {
                type: DataTypes.TEXT,
                primaryKey: true
            },
            // Other computer fields
        });

        const flags = postgresDB.define('flag', {
            id: {
                type: DataTypes.TEXT,
                primaryKey: true
            },
            name: DataTypes.TEXT,
        });
        const computerFlags = postgresDB.define('computerFlag', {}, { createdAt: false, updatedAt: false })

        computers.belongsToMany(flags, { through: computerFlags });
        flags.belongsToMany(computers, { through: computerFlags });
        await postgresDB.sync({ alter: true })
        const c = await computers.count({


            distinct: true,
            group: ['computer.name'],
            include: [

                {
                    model: flags

                },
            ]
        });
        } catch (err) { console.log(err) }
})();

When using the following SQL query, I get a partially correct result:

select count("computerName") from "computerFlags"
group by "computerName"
having '2' != all(array_agg("flagId"))

However, I am unable to replicate this behavior in Sequelize. Also, based on the table provided, the mentioned query would return 1 as 'computer3' is absent from the list.

To execute this functionality using Sequelize, I would ideally like to implement something similar to the following:

having: {
  [[Sequelize.fn('array_agg', Sequelize.col('flag.id')), 'flagIds']] : {
    [Op.all]: {
      [Op.ne]: '2'
    }
  }
}

There are two main issues with this approach:

  1. I am unable to use [[Sequelize.fn ...]] as the left operand
  2. The referencing of the flag ID might be incorrect, since it should resemble something like computer->flags->flagId. When utilizing findAll, computer->flags returns an array of flags where each contains flagId.

I am currently quite perplexed and would greatly appreciate any guidance you can offer.

Answer №1

I'm looking to run a query that will calculate the total number of computers that do not have "flag3".

To achieve this, you can utilize NOT EXISTS. (Some might refer to it as a "semi-anti-join".)

SELECT count(*)
FROM   computers c
WHERE  NOT EXISTS (
   SELECT FROM computerFlags cf
   WHERE  cf.computerName = c.computerName
   AND    cf.flagId = 'flag3'
   );

This method only excludes computers from the count if they have an entry with 'flag3'.

It is considered to be more efficient in terms of performance.

On a side note: using CaMeL case names may not be optimal for Postgres. For more information, refer to:

  • Are PostgreSQL column names case-sensitive?

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

transferring documents using multer

As a novice in JavaScript, I am exploring the use of multer for file uploads. Below is my current code: let express = require('express'); let im = require('imagemagick'); let gm = require("gm").subClass({ imageMagick: true }); let ...

Django's Implementation of Real-Time WebSocket Notifications

Currently, I am encountering an issue while integrating web socket notifications into my Django project. The problem arises when attempting to pass the user's unread notification count to them. To address this challenge, my initial solution involved ...

Establishing global date restrictions for the DatePicker component in Angular 8 using TypeScript across the entire application

I am currently learning Angular 8 and I am looking to globally set the minimum and maximum dates for a datepicker in my application. I would like to accomplish this by using format-datepicker.ts. Any suggestions on how I can achieve this? Min date: Jan 1, ...

Sequelize Error: Undefined property 'define' being accessed

I am attempting to add a new record to a MYSQL table using sequelize. After installing sequelize and mysql, I ran the following commands: npm install --save sequelize npm install --save mysql In my app.js file, I included the following: var Sequelize ...

JavaScript facing issue with $.get command executing in incorrect order

I have encountered an issue with my JavaScript code where it is not running in sequence. The script includes an unload function that uses the $.get jQuery command to fetch a file, which is then supposed to be printed to an external device. To debug this ...

Is AGM-Map capable of providing all the same features as the Google Maps API?

Greetings to everyone! I am currently working on an Angular 6 project and I want to incorporate asset tracking using the Google Maps API. However, I am unsure if AGM-Map fully supports all the features of Google Maps API, like heatmaps and advanced asset ...

After an ajax call in ASP .NET MVC3 using Razor, jQuery may not function properly

When I perform a post back to obtain a partial view using ajax, I utilize the following code to render the partial view within a div named 'DivSearchGrid'. <script type ="text/javascript" > $('#Retrieve').click(function ( ...

The default behavior of Angular-Keycloak does not include automatically attaching the bearer token to my http requests

I'm currently working on integrating keycloak-angular into my project, but I'm facing an issue with setting the bearer token as the default for my HTTP requests. "keycloak-angular": "9.1.0" "keycloak-js": "16.0 ...

Utilize the power of XMLHttpRequest to fetch and load numerous audio files, seamlessly integrating them for playback through the Web Audio

I am looking to create a web application that loads three different audio files, each one second long, in a specific order, and then merges them into a single Audio Buffer consecutively. To illustrate my goal, here is a sample code snippet: var AudioCo ...

Angular: How to Disable Checkbox

Within my table, there is a column that consists solely of checkboxes as values. Using a for loop, I have populated all values into the table. What I have accomplished so far is that when a checkbox is enabled, a message saying "hey" appears. However, if m ...

Retrieve the value of a dynamically generated input element within a form object

I'm trying to figure out how to reference a dynamic 'name' of an input element in a form. Can anyone help? Here's an example using HTML: <form> <input type="text" name="qty1" value="input1" /> <input type="text ...

Creating a Timeout Function for Mobile Browsers in JavaScript/PHP

Currently, I am developing a mobile-based web application that heavily relies on AJAX and Javascript. The process involves users logging in through a login page, sending the data via post to the main page where it undergoes a mySQL query for validation. If ...

What steps should I take to ensure that the <select> tag is compatible with Microsoft Edge?

Currently, I am working on editing jsp files that utilize struts1. <html:select property="someProperty" style="width:110;height:110" styleClass="someClass"> However, when viewing it in Microsoft Edge, I noticed that the drop-down menu already ...

Steps for automatically adding a new user to the AddThis service for configuring analytics services

As I work on creating a Backoffice for my website, I am looking to provide a mobile version for all users uniformly. To enhance user experience, I plan to introduce a "Report" tab in the back office interface. This tab will display analytics information g ...

Incorporate new content into JavaScript using the input element

I have a unique question - can text be added to JavaScript using the input tag? For example, <input type="text" id="example" /> And let's assume the JavaScript function is: function display_text() { alert("The text entered in #example wi ...

Is there a way to merge the .load function and the document.referrer function together?

Is there a way to load a specific div from the previous page that a user originated from using a form? $(document).ready(function() { $("#div_to_be_populated").load('url #div'); }); How can I utilize the document.referrer function in the ur ...

When we modify the prototype of the parent object, where does the __proto__ point to?

Typically, when a new object is created using the "new" keyword, the __proto__ property of the newly created object points to the prototype property of the parent class. This can be verified with the following code: function myfunc(){}; myfunc.prototype.n ...

When using Ionic, clicking on a Google Maps marker to navigate to another page with NavController can sometimes result in the clicks on the new

Upon successfully displaying the pushed page, I encountered a strange issue where all elements with a (click)='doSomething()' binding stopped working throughout the newly loaded page. Additionally, there was an ion-slides element on the pushed pa ...

Modifying Copyright Feature in Footer

I am attempting to implement this function within my dark-colored footer: import Typography from '@material-ui/core/Typography'; function Copyright() { return ( <Typography variant="body2" color="textSecondary" align="center"> ...

Unable to dynamically add an element to a nested array in real-time

I'm currently developing an angular tree structure that contains a large nested array. nodes : public fonts: TreeModel = { value: 'Fonts', children: [ { value: 'Serif - All my children and I are STATIC ¯\ ...