Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to combine columns in knex.js

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?

like image 547
surajck Avatar asked Feb 09 '15 14:02

surajck


People also ask

What is KNEX JS?

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.

How do I pull data from two tables in KNEX?

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.

How do I run a raw SQL query in KNEX?

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.

Can I use KNEX raw parameter bindings in a query?

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


1 Answers

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?"

like image 166
Clown Man Avatar answered Sep 20 '22 20:09

Clown Man