Is there a way to use Knex to transform the relevant rows of a joined table into a nested object structure?

How can I retrieve a user's relevant row from the users table using knex, along with an array of all the groups associated with a user whose id is 1?

Here is the structure of my users table: https://i.sstatic.net/9lhPZ.png

This is the setup of my groups table: https://i.sstatic.net/A4aMf.png

And this is the schema for my users_groups association table: https://i.sstatic.net/3TrD8.png

Despite running a query, it currently returns three separate rows for the same user:

db("users").join("users_groups", "users.id", "=", "users_groups.user_id").join("groups", "groups.id", "=", "users_groups.group_id").where("users.id", "=", 1)

The SQL equivalent of this query is as follows:

select * from users inner join users_groups on users.id = users_groups.user_id inner join groups on groups.id = users_groups.group_id where users.id=1

The current output is:

Array(3) [Object, Object, Object]
length:3
__proto__:Array(0) [, …]
0:Object {email:"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3d4f5c577d4f5c57134f5c57">[email protected]</a>" group_id:1, id:1, name:"step 1", name:"r", role:"superadmin", user_id:1, username:"raj"}
1:Object {email:"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1664777c5664777c3864777c">[email protected]</a>" group_id:2, id:1, name:"step 2", name:"r", role:"superadmin", user_id:1, username:"raj"}
2:Object {email:"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ee9c8f84ae9c8f84c09c8f84">[email protected]</a>" group_id:3, id:1, name:"step 3", name:"r", role:"superadmin", user_id:1, username:"raj"}

In stringified format, it appears like this:

"[{"id":1,"name":"step 1","email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="bdcfdcd7fdcfdcd793cfdcd7">[email protected]</a>","username":"raj","password":"$2b$10$GbbLTP2sEPS7OKmR4l8RSeX/PUmoIFyNBJb1RIIIrbZa1NNwolHFK","role":"superadmin","created_at":"2020-04-14T12:45:38.138Z","user_id":1,"group_id":1},{"id":2,"name":"step 2","email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="384a5952784a...

An ideal output would be an object representing the user along with nested objects for the relevant group rows from the groups table, such as:

{id:1, name:"raj", groups:[{id:1, name:"step 1"}, {id:2,name:"step 2"}, {id:3,name:"step 3"}]}

Is there a possibility to achieve this in a single query or would multiple queries be necessary, and how efficient would that be?

Answer №1

Unfortunately, Knex doesn't have the capability to aggregate flat data as per your requirements. You'll need to handle this task manually.

(await db('users')
  .join('users_groups', 'users.id', '=', 'users_groups.user_id')
  .join('groups', 'groups.id', '=', 'users_groups.group_id')
  .where('users.id', '=', 1)
  )
  .reduce((result, row) => {
    result[row.id] = result[row.id] || {
      id: row.id,
      username: row.username,
      email: row.email,
      groups: [],
    };

    result[row.id].groups.push({ id: row.group_id, name: row.name });
    return result;
  }, {});

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

Tips for incorporating additional items into an established useState array utilizing map() or foreach()?

I'm working on developing a social media platform similar to Twitter, and I'm facing challenges with the news feed functionality. Essentially, the news feed is supposed to fetch tweets from my firebase database for each user followed by the curre ...

Querying a JSON field in BigQuery yields empty results

Once more, I am struggling with my SQL query on a JSON field in bigquery. This JSON data can be found at this link - The specific record I am working with has an id of 1675816490 Here is the SQL statement I am using: SELECT ##JSON_EXTRACT(jso ...

Tips for replacing multiple values within a single column in a MySQL SELECT query by utilizing the REPLACE() function

I am facing an issue with converting Boolean values (0 and 1) in a table to CSV format for a client. I have figured out how to replace the value of '1' with 'Yes' using the following query: SELECT REPLACE(email, '%40', ' ...

An issue has arisen with the TypeScript function classes within the React Class, causing a compile error to be thrown

I am currently in the process of transitioning a React object from being a function to a class. This change is necessary in order to save the state and bind specific functions that I intend to pass to child components. Unfortunately, during compilation, I ...

Tips for developing a directive that supplies values for ng-options

I have select elements with the same options throughout the entire app, but they may vary in appearance. For example, selects for a user's birthday (day, month, year). Is it possible to create a directive that can provide values or expressions for ng ...

Selecting a event from Google Places Autocomplete using a mouse click

I have successfully implemented Google's autocomplete API as per the documentation. However, I am facing an issue with a form that is submitted via Ajax every time it changes. The problem arises when using the autocomplete feature for location selecti ...

I am unable to halt the relentless stream of asynchronous events

Struggling to retrieve an array using a loop in the asynchronous environment of nodejs. Check out my code below: getDevices(userIDs, function(result) { if (result) { sendNotification(messageUser, messageText, result); res.send("Success"); } else { ...

Use regular expressions in JavaScript to replace text patterns

Is there a way to paste formatted text from Word or a web page into an HTML5 textarea without the formatting, but still keeping the line breaks? I attempted to extract the raw text and then use regex and Javascript's replace method to add line breaks ...

The sharpness of images may diminish when they are created on an HTML5 Canvas within Next JS

I am currently working on a project where users can upload an image onto an HTML5 canvas with fixed dimensions. The uploaded image can be dragged and resized using mouse input while preserving its aspect ratio. Below is the draw function I am using to achi ...

Struggling to configure an input field using ExtJS

I am trying to use an onChange event to update an input field with the selected option. Below is my code: HTML: <select id="builds" onchange="setBuild()"> <option value="select">Select</option> ... </select> <input ty ...

Grab the current URL using useRouter in a Next.js app

I am using userouter to obtain the URL of the current page and then utilizing the clipboard to copy it. However, I am encountering an issue where the copied content shows as object object instead of the expected URL. Can someone please help me identify w ...

Encountering CORS Issue when attempting to upload a file from an external URL using Angular

I am attempting to upload a file from an external URL, but I keep encountering a CORS error when trying to access the external URL. await fetch(url).then(function (res) { response = res; }).catch(function () { setTimeout(() => { this.toaster. ...

What could be causing AngularJS to fail to send a POST request to my Express server?

I am currently running a Node Express server on localhost that serves a page with AngularJS code. Upon pressing a button on the page, an AngularJS controller is triggered to post a JSON back to the server. However, I am facing an issue where the post requ ...

Tips for creating ui-sref links by using a mix of translate and ng-bind-html

I'm having trouble figuring out how to create a functional ui-sref link from a translated string. Using angular 1.4.9 along with angular translate 2.9.0 Below is the relevant code snippet <div ng-bind-html="$scope.getTranslatedText(someObject)"& ...

Why is React's nested routing failing to render properly?

click here for image portrayal I am currently attempting to integrate react router, specifically a nested router. However, when I click the links on the contact page, no results are being displayed. Any assistance would be greatly appreciated. For more in ...

Is there a way for me to showcase information?

I am currently facing an issue with displaying user information retrieved from my database using AngularJS. The code snippet below shows how I am trying to get the user data: angular.module('listController',[]) .controller('listCtrl' ...

Trouble arises when attempting to transpile a Node.js application using gulp-babel's ignore feature

I've set up a gulp task to transpile my Node.js app: gulp.task('babel', function() { return gulp.src('./**/*.js') .pipe(babel({ ignore: [ './gulpfile.js', './ ...

Layout of CSS grid being created dynamically

The concept of the CSS grid layout, as explained here, demonstrates that the grid cells are structured in the markup without hierarchy. The arrangement into rows and columns is managed through CSS directives like grid-template-columns. An illustration for ...

Creating a Date Computation Tool that Adds Additional Days to a Given Date

I have a challenge where Date 0 represents the start date, Date 1 is the result date after adding a certain number of days (NDays). I am looking for help in JavaScript to calculate Date0 + NDays = Date1. Please assist me as my coding knowledge is quite l ...

The replacement of classes in ReactJS using JavaScript seems to be malfunctioning

I have been attempting to change the class of a dynamic element when clicked, but none of my solutions seem to be working. Here is what I have tried: handleClick=(event,headerText)=>{ document.getElementsByClassName('sk-reset-filters') ...