Tips for incorporating 'and' in the 'on' clause of 'join' in knex.js

I need assistance implementing the following SQL code in knex.js:

select c.id,c.parent_id,c.comment,u.username,c.postid from comments as
     c join post_details as p on (p.id = c.postid and c.postid=15)join
     users as u on (u.id = c.userid);

I attempted to do this using the following JavaScript code:

db('comments AS c')
  .join('post_details AS p', function () {
    this.on('p.id', '=', 'c.postid').on('c.postid', '=', db.raw('?', [postid]));
  })
  .join('users AS u', 'u.id', '=', 'c.userid')
  .select(['c.id', 'c.parent_id', 'c.comment', 'u.username', 'c.postid', 'c.userid'])
  .then((data) => {
    console.log(data);
    res.json(data);
  })
  .catch((err) => res.status(400).json('unable to fetch'));

However, I am encountering issues with fetching the data when calling the URL.

Your help with resolving this matter would be greatly appreciated. Thank you in advance.

Answer №1

Give this a shot:

db('comments AS c')
  .join('post_details AS p', (joinBuilder) => {
    return joinBuilder.on('c.postid', '=', 'p.id').andOn(db.raw('?', [postid]), '=', 'c.postid');
  })
  .join('users AS u', 'u.id', '=', 'c.userid')
  .select(['c.id', 'c.parent_id', 'c.comment', 'u.username', 'c.postid', 'c.userid'])
  .then((data) => {
    console.log(data);
    res.json(data);
  })
  .catch((err) => res.status(400).json('unable to retrieve data'));

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

Automatic line breaks in MathJax when displayed in a modal dialogue box

As part of a math project, I need to display the solution of a problem in a Sweetalert2 modal. However, despite using the following code: <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: { inlineMath: [['$','$ ...

Removing jQuery error label from an HTML block

I need a single command that will remove an error label from my HTML when the field content is changed. It currently works on input and select elements, but not within an input-group. I am looking for a solution that will work universally across all instan ...

I'm looking for a way to display the value stored in a variable within an ejs template. Any suggestions

I am experiencing an issue with my ejs template that should greet the user by displaying their name when the page loads, but it is not showing anything. Here's a snippet of my template: <!DOCTYPE html> <html> <head> < ...

Creating a simulation in THREE.js that incorporates MeshBasicMaterial, with the added feature of being able to

Creating a dungeon crawler game using three.js has been quite the learning experience. Initially, I opted for MeshBasicMaterial to ensure everything was uniformly visible in the dungeon. However, I wanted to experiment with adding bonus lights peeking thro ...

Tips for updating a field-List in MongoDB with Mongoose and Node.js

Hello there Stackoverflow team, I'm currently working on updating a user model in my nodeJs application using Express and Mongoose (MongoDB) to handle multiple "devices". Here's what my User model looks like: const userSchema = new Schema({ ...

Implementing a constant loop repeatedly in NextJs

I am seeking assistance with printing the <Icon /> 700 times on a single page. As a newcomer to NextJs, I have successfully used a for loop to console.log the icons but am unsure of how to actually display them. Any help would be greatly appreciated. ...

What is the simplest way to retrieve inner JSON elements using Simple JSON in Java?

Here is an example of JSON data: { "messages": [{ "tax_number": "111", "creation_date": "29.11.2019 07:52:24", "request_id": "222", "type": "REQUEST", "id": "333", "details": "duplicate for VAT number 111" }, { "tax_number": "4 ...

Experimenting with NGXS selectors: A comprehensive guide

Hey there, I am currently utilizing the NGXS state management library in my application. I have a selector set up like this and everything seems to be functioning correctly. However, while testing the app, I encountered the following error message: "PrintI ...

What are the steps for starting an Express EJS project using the command line?

I attempted the following: Ran express -e myproject Unfortunately, this did not produce the anticipated results ...

Is there a parameter I am overlooking when trying to remove an item from a state-stored array using the delete button at line 55?

Need help with the code in the app component. I know it's not ideal, any assistance would be greatly appreciated. I'm a bit lost and can't figure out how to remove an item from the list after it has been added. Everything else seems to work ...

Save and showcase SQL, PHP, HTML, and JS code exactly as it is preserved in MYSQL database

Is there a way to store and display complete JS, PHP, and HTML code in MySQL without altering the format? The stored PHP code should appear as: <?php echo "something"; ?> And not just: something For JavaScript: <script> document.write(&ap ...

React.js encountered an error: Unexpected "<" token

My journey with react.js has just begun. I am currently using Webstorm for development. I have encountered an error that I am struggling to solve. It seems like React is not being recognized even after trying to install various npm react packages. Synta ...

Substitute the symbol combination (][) with a comma within Node.js

Currently, I am utilizing Node JS along with the replace-in-file library for my project. Within a specific file named functions.js, I have implemented various functions. Furthermore, in another file named index.js, I have added code to call these functio ...

Adjust the hue of a specific node

Is there a way to customize the color of an individual node in an eChart treemap? I attempted to set a color property for the node, but it didn't seem to work. While I was able to change the label's color, I'm interested in changing the back ...

Forming a BoxBufferGeometry using the dimensions from Box3

I'm looking to generate a box mesh within a three.js scene, with the points of the box mesh matching the bounding box of an existing object in the scene. I attempted to create the box mesh from box3 using the method outlined below, but I'm not a ...

Unable to alphabetically arrange buttons automatically

I am encountering a challenge with automatically sorting buttons alphabetically on my webpage. I am unable to determine the method for sorting these buttons using jquery or javascript, but my goal is to have them sorted automatically when the page loads. I ...

The hierarchy of Android classes for handling JSON data with multiple elements

My Android app retrieves a JSON data from an HTTP call that has the following structure: { "string_1":{ "prop_1":"value", "prop_2":"value" }, "string_2":{ "prop_1":"value", "prop_2":"value" }, ... "string_n":{ ...

Using AngularJs, you can access the document.body.onfocus event within the controller of

I am attempting to detect when the user closes or cancels the File Upload Window <input type="file"> Since there isn't a built-in listener for the close event of the file upload, I am trying to capture it using the document.body.focus event, s ...

Tips for utilizing props in a Vue component

When trying to incorporate a prop into a computed value, I encounter the following error: [Vue warn]: Error in render: "TypeError: Cannot read property 'length' of undefined" found in ---> at src/cmps/space-details/space-imgs.vue at src/pa ...

Unexpected results from the match() function

Attempting to utilize the RegExp feature in Javascript (specifically with the match function) to locate instances of a sentence and a specific word within that sentence embedded in the HTML body. Provided is some pseudo-code for reference: <!DOCTYPE ...