Creating One to Many Table Joins with Knex.js

My current situation involves working with two tables:

In the quotes table, we have columns such as first_name, email, estimate, and more.

Then, there's the quote_notes table with columns like id, note, and quote_id.

The relationship between these tables is that quotes has_many quote_notes. I'm attempting to incorporate this join in my query within the quote model.

function getAllNotes() {
  return db('quote_notes')
    .select('quote_notes.id', 'note', 'quote_notes.created_at', 'quote_id')
    .join('quotes', 'quote_notes.quote_id', 'quotes.id')
    .orderBy('id')
}

Upon sending a GET request to the specified path, the response includes all quote_notes associated with any quote being viewed.

router.get('/:id/notes', (req, res) => {
  const {id} = req.params;

  Quotes.getAllNotes(id).then((users) => {
    res.status(200).json(users);
  });
});

For clarification purposes, here's the request:

const getQuoteNotes = async () => {
  let quoteNotes = await axiosWithAuth().get('/quotes/' + quoteId + '/notes');
  setQuoteNotes(quoteNotes.data);
  }

Lastly, here's an overview of the quote_notes table structure:

table.bigInteger('quote_id')
      .unsigned()
      .index()
      .references('id')
      .inTable('quotes')

Answer №1

Prioritize the use of "join" before "select"

return db('quote_notes')
  .join('quotes', 'quotes.id','=', 'quote_notes.quote_id')
  .select('quote_notes.id', 'note', 'quote_notes.created_at', 'quote_id')
  .orderBy('id')

Your recent modification has an impact; if you only require notes for a specific quote, query using the quote_id

db('quote_notes')
.where('quote_id', quoteId )
.orderBy('id')

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

Issues with rendering of triangles in WebGL

My current project involves creating a webGL application for rendering randomly generated terrains. While the terrain rendering works smoothly, I've encountered an issue with rendering a simple quad to represent water - the triangles of the water are ...

What causes the lack of impact on lambda rendering speed despite integrating webpack?

Hey there, I've been working on implementing webpack for a project that involves microservices, Node.js, TypeScript, AWS, and AWS SAM. My main objectives are: Reduce the cold start time of lambda functions. Minimize security vulnerabilities by e ...

Creating PHP functions that return a JSON string when invoked - a simple guide

I have created a script that contains various functionalities, including fetching data from a database and encoding it into JSON. However, I want to be able to call different functions to execute these scripts separately. When I attempted to define and c ...

tips for modifying html element attributes using angular

I am working with an element that is automatically generated through an API call as <a target="_blank" href="http://www.work.com/reward"><b class="orange tdu">My Work History</b></a> and now I want to modify it like <a ng-cl ...

Implementing theme in Monaco editor without initializing an instance

I recently developed a web application incorporating Monaco Editor. To enhance user experience, I also integrated Monaco for syntax highlighting in static code blocks. Following guidance from this source, I successfully implemented syntax highlighting wit ...

Exploring the Possibilities of Message Embeds in Discord using JavaScript

My goal is to teach my bot how to scan the description of embeds for a specific phrase. After reviewing the documentation at https://discord.js.org/#/docs/main/v11/class/MessageEmbed?scrollTo=description, it appears that I need to implement code similar to ...

Basic HTML Audio Player Featuring Several Customizable Variables

I have a unique API that manages music playback. Instead of playing audio in the browser, it is done through a Discord bot. Achievement Goal https://i.stack.imgur.com/w3WUJ.png Parameters: current: indicates the current position of the track (e.g. 2:3 ...

Issue with Vue Composition API: Unable to append a property to an object

Currently, I am utilizing Vue's Composition API in my project. However, I have encountered an issue where the template renderer does not recognize changes when I add a property to a ref object. Below is the code snippet that demonstrates this problem: ...

Creating a persistent sticky element that remains at the forefront in Electron or JavaScript development

Currently, I have a remote desktop control application built on Electron that functions as a desktop app on Mac and Windows, and as a web app on Chrome and Firefox. My next goal is to create a sticky component that remains on top at all times, regardless ...

AngularJS function orderBy reverses the array instead of sorting it

I encountered an issue where, after clicking the 'order button', the table does not order as expected. Instead, it reverses all the td elements. For example, 'A', 'C', 'B' becomes 'B', 'C', "A". I ...

Deselect a selected radio button by clicking on it

I am trying to create a radio button with an unchecked value, and I thought this code would work: $('form').on('click', 'input[type="radio"]:checked', function (event) { $(this).prop("checked", false); }); It seems simpl ...

Choose from a range of knockout fetching options for the select feature and choose one

Upon loading my page, there is a <select> element positioned. I am utilizing knockout data-bind to retrieve the values like this: <select data-bind="attr: { id: 'input-' + id(), required: !allowBlank }, option ...

How to Make a Div Tag Fade Effect with JavaScript in an External File

*** New Team Member Notice *** I'm currently working on an assignment and trying to implement a simple fade effect on a box. While it seems like this should be straightforward, I'm encountering some obstacles. Currently, the button causes the bo ...

Display all information associated with the class that matches the clicked ID

Can anyone help me with a Jquery question? I am trying to display all data with the same class when I click on it. I have created a list of clickable items. When I click on an item, the corresponding data should be shown. However, the code I wrote is not ...

Ensure Vue line chart stays current with data passed in as props

Vue 2.x chart-js: 2.x vue-chartjs: 3.x I am currently working on a project where I need to send data from a websocket in my parent component to a child component to create a dynamic line chart that updates in real-time. In my Parent.vue file: <templ ...

The mobile menu functions correctly on Jfiddle but is not functioning on the local server

I was working on a responsive mobile menu and used a toggleClass function to open the menu. It's functioning correctly in Jfiddle and below, but every time I click the nav icon in the live preview within brackets, nothing happens. I even tried it in a ...

Display a different image while another image is in the process of loading

I am currently facing an issue with a div that has a background image set up as follows: <div class="carousel-image" style="background: url(img/background.gif) no-repeat center center;"> </div> Upon loading my webpage, there is a brief ...

What is the process for showing a duplicate image in a dialog box once it has been selected on an HTML page?

I am experiencing an issue where the dialog box is displaying when I use the button tag, but not when I use the image tag. Can someone please assist? <img src='image.png' height='200px' widht='200px' id='1'> ...

Arrays cannot be used with $addFields in MongoDB

I have encountered a challenge where I am dealing with a field that can be either a string or an array. How can I handle this scenario in the $addField query? Below is my MongoDB query code snippet: db.ledger_scheme_logs.aggregate([ { $match ...

Display Material checkbox based on a condition

I have integrated Material UI into my React application to dynamically display text and other information by using JSON data. { "included": [{ "name": "someName", "price": "0", "required": true } ...