Tips for converting a raw SQL query to Knex syntax

Recently delving into the world of development, I've come across knex for the first time.

Issue: I have a raw SQL query that is functioning correctly. Now, I'm attempting to utilize knex for this query. To better understand how things operate, I would like to:

  1. recreate the query with knex.raw
  2. recreate the query using the knex query builder.

Can anyone assist me with this task? By the way, I am using Postgres and Next.js. Upon running the code below, I encounter an "UnhandledPromiseRejectionWarning: Error: Expected 1 bindings, saw 0". I am uncertain whether the problem lies within this snippet:

typeof req.query.word === 'string' ? [req.query.word] : req.query.word)

...so I made an attempt to rewrite it by adding square brackets, but without success. Here is the code provided:

const getTranslation = (req, res) => {
  const params =
    typeof req.query.word === 'string'
      ? req.query.word
      : req.query.word.map((_, index) => `$${index + 1}`);
    console.log(req.query.word);

  knex.raw(
    `SELECT "Translation", "Words" FROM "Dictionary" WHERE "Words" IN (${
      typeof req.query.word === 'string' ? '($1)' : params.join(',')
    })`,
    typeof req.query.word === 'string' ? [req.query.word] : req.query.word)
    
      .then((error, result) => {
        const wordArray = typeof req.query.word === 'string' ? [req.query.word] : req.query.word;
        if (error) {
          throw error; 
        } 
        const wordOrder = req.query.word;
        result.rows.sort((row1, row2) => {
          return wordOrder.indexOf(row1.Words) - wordOrder.indexOf(row2.Words);
        });
        res.status(200).json(result.rows);
    }
  );
};

Attempts Made: To verify if the setup was correct, I experimented with a simple query. Based on my observation, everything seems to be in order: a request with status 200 is visible in the terminal (network) and I can see the data in the console...

const getTranslation = (req, res) => {
  knex.select("Words", "Translation").from("Dictionary")
      .then(rows =>
        rows.map(row => {
          console.log(row)
        }))
} 

Thank you!!

Answer №1

For optimal results, your query should take the following form:

Let results = await knex('Dictionary')
  .select(['Translation', 'Words'])
  .whereIn('Words', req.query.word); // assuming that `req.query.word` is an array containing strings/numbers

Answer №2

Keep in mind that I have limited knowledge of Knex.

However, as I was reading responses to a related question on the link provided below, I noticed that many of them recommended using "Knex.with()".

How to add two bind params in knex?

knex.with('with_alias', knex.raw('select * from 'lyrics' where 'for_id' = ? and 'var' = ?', [var1, var2])).select('*').from('with_alias')

It seems that they are suggesting binding it with 'With_alias'.

Additionally, they advised passing variables in the array.

I trust this information will provide some assistance to you.

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

What is the most effective way to integrate a Link/URL button into the remirror toolbar?

I have chosen to utilize remirror for constructing a WSYWIG editor. The specific requirement is to include a "Link" icon in the toolbar, allowing users to select text and easily add a hyperlink by clicking on it. Although I came across the LinkExtension ...

The total height of an HTML element, which takes into account the margin of the element itself

Is there a way to accurately calculate the height of an element including margins, even when dealing with child elements that have larger margins than their parents? HTMLElement.offsetHeight provides the height excluding margin, while this function from ...

Discover the Next.js App Directory: Automatically refresh the client component when an async function is completed. No need to manually refresh the page for

Seeking assistance with updating a client component in Next.js without a SRC folder and using app router. The component is part of a globally present menu and should update when the user logs in, but currently only refreshes after a browser reload. Various ...

Check if a user is currently on the identical URL using PHP and JavaScript

In my Laravel and AngularJS project, I have a functionality where users can view and edit a report. I'm looking to add a feature that will prevent multiple users from editing the report at the same time - essentially locking it while one user is makin ...

Calculate the duration in seconds using the console

Is it possible to display the time of an action in seconds instead of milliseconds using console.time? Below is my code: console.log('start load cache'); console.time('cache load ok executed in') // loading from mongo console.timeEnd( ...

Transmitting the Flag between PHP and JavaScript

I need help with setting a flag in PHP and accessing it in JavaScript. Currently, I have the following code: PHP if ($totalResults > MAX_RESULT_ALL_PAGES) { $queryUrl = AMAZON_SEARCH_URL . $searchMonthUrlParam . ...

What are the steps to incorporate ThreeJS' FontLoader in a Vue project?

I am encountering an issue while attempting to generate text in three.js using a font loader. Despite my efforts, I am facing difficulties in loading the font file. What could be causing this problem? const loader = new FontLoader(); loader.load( ' ...

Ways to insert text into an SVG file

I am currently using vue-svg-map with a USA map. I am trying to display the state code (path.id) on my svg map. Can anyone provide guidance on how to achieve this? <radio-svg-map v-model="selectedLocation" :map="usa" :location-class="getLocation ...

PHP and AJAX concurrent session issue causing difficulties specifically in Chrome browser

TL;DR. I'm encountering an issue in Chrome where different requests are seeing the same value while incrementing a session counter, despite it working fine in Firefox and Internet Explorer. I am attempting to hit a web page multiple times until I rec ...

Having trouble selecting the clicked element after a successful Ajax call, especially when there are multiple elements with the same name

When dealing with multiple elements that share the same class name, I am attempting to target the 'clicked' element upon a successful Ajax return. <td data-name='tom' class="status"><a href="">click< ...

How can material-ui useScrollTrigger be utilized in combination with a child's target ref?

Attempting to utilize material-ui's useScrollTrigger with a different target other than window presents a challenge. The code snippet below illustrates an attempt to achieve this: export default props => { let contentRef = React.createRef(); ...

What is the best way to incorporate server-side rendered content from a CMS to hydrate Vue.js?

Consider this scenario: content is managed through a traditional CMS such as Joomla or Drupal content is provided by the CMS as fully rendered HTML and CSS In the Frontend React.js should be utilized for all UI interactions. Despite going over most of R ...

Determine which JavaScript script to include based on whether the code is being executed within a Chrome extension

I am in the process of developing a Chrome extension as well as a web JavaScript application. I currently have an HTML container. I need the container.html file to include <script src="extension.js"> when it is running in the Chrome extension, and ...

Stripping out only the position attribute using jQuery

I have implemented a code with the following characteristics: The navigation items' texts are hidden behind certain Divs, which I refer to as Navigation Divs. When the mouse hovers over these pixels (navigation Divs), the text that is behind the ...

Display various divs simultaneously based on the quantity of items in the dropdown menu

In my project, there is a dynamic select list that retrieves items from the database. Users have the ability to add or delete items from this list. Below is some code related to this functionality: <div class="form-group col-md-3"> <la ...

Do [(ngModel)] bindings strictly adhere to being strings?

Imagine a scenario where you have a radiobutton HTML element within an angular application, <div class="radio"> <label> <input type="radio" name="approvedeny" value="true" [(ngModel)]=_approvedOrDenied> Approve < ...

Trouble with using $.ajax to call a PHP function

Hey everyone, I hate to ask for help but I'm really stuck on this issue. I've tried everything and followed all the scenarios on this site, but I just can't seem to get it working. I even added alerts and echoes, but the function doesn' ...

Transforming the typical click search into an instantaneous search experience with the power of Partial

I am working on a form that, when the user clicks a button, will display search results based on the entered searchString. @using (Html.BeginForm("Index", "Search")) { <div id="search" class="input-group"> @Html.TextBox("searchString", n ...

Convert the contents of the uploaded file to a JSON format

I've recently started using angularjs for file uploads and came across this helpful model on github: https://github.com/danialfarid/angular-file-upload The file upload process is working smoothly for me. However, I'm facing a challenge after upl ...

Remove any URLs and replace them with a text corresponding to the ID of the selected link

I need assistance with a JavaScript code. I have three links, each with a different ID. What I am trying to achieve is that when I click on one of these links, the script should grab the ID, delete all three links, and replace them with text in their place ...