How can I write select firstName || ' ' || lastName as name
in knexjs. Using raw this way .columns(knex.raw("fname || ' ' || lname as name"))
works, but is there any other way?
This Knex.js Tutorial will be beginner friendly with code examples so all users can benefit most from it. Knex.js is a very popular Node.js SQL query builder with supports both callback and promise based coding styles, transaction with save points support for all major SQL databases with common api interface for all queries.
To achieve this outcome, we need to join two tables ( users, and posts) and create a query in Knex that pulls data from both tables. This code creates a route that retrieves the posts with a specific user id. If we want to grab data from the users table, though, we need a join statement in our query.
In psql or your GUI tool run the following command. Unfortunately, Knex does now support a similar syntax. It does, however, support a raw SQL using the knex.raw () method. Please note, knex.raw () passes the query as-is which can open you up to SQL injection attacks.
Please note, knex.raw () passes the query as-is which can open you up to SQL injection attacks. Do not use this approach for user-entered values until to your understand SQL-injection attacks and Knex Raw Parameter Bindings. Try It! Update the knex query in the .get endpoint with the following
You could also just combine it in the code itself, why combine it in the query, when the same work can be done inline with the results of your query. It would be easier to read at that point, and you can do other stuff to the string before handing it out.
PS: You did ask "is there any other way?"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With