Knex: Column name alias

Created on 30 Sep 2013  路  1Comment  路  Source: knex/knex

Hello,

is there possibility to use aliases for columns?

For example my object contains field named 'firstName' however
mysql table has it as 'first_name' (because of convention).

Is there any possibility to map column name to object field?

I tend to use auto-generated insert without any raw query writing,
and seems to be I need to have object field names the same as they
written in the database.

Any thoughts on this?

question

Most helpful comment

Hey @pro100sanya - for now, on selects you can do something like:

.select('first_name as firstName', 'last_name as lastName')

but it sounds like you're asking more about inserts. I'm afraid that this is something I'm going to leave out of Knex for now, since it should be simple to pre-format the object as needed with underscore methods before inserting into the db:

var aliases = {
  firstName: 'first_name', 
  lastName: 'last_name'
};
var data = [
  {firstName: 'Test', lastName: 'User'}, 
  {firstName: 'Test2', lastName: 'User2'}
];
knex('accounts').insert(_.map(data, function(row) {
  var key, data = {};
  for (key in row) {
     data[aliases[key]] = row[key];
  }
  return data;
}));

// insert into `accounts` (`first_name`, `last_name`) values ('Test', 'User'), ('Test2', 'User2');

>All comments

Hey @pro100sanya - for now, on selects you can do something like:

.select('first_name as firstName', 'last_name as lastName')

but it sounds like you're asking more about inserts. I'm afraid that this is something I'm going to leave out of Knex for now, since it should be simple to pre-format the object as needed with underscore methods before inserting into the db:

var aliases = {
  firstName: 'first_name', 
  lastName: 'last_name'
};
var data = [
  {firstName: 'Test', lastName: 'User'}, 
  {firstName: 'Test2', lastName: 'User2'}
];
knex('accounts').insert(_.map(data, function(row) {
  var key, data = {};
  for (key in row) {
     data[aliases[key]] = row[key];
  }
  return data;
}));

// insert into `accounts` (`first_name`, `last_name`) values ('Test', 'User'), ('Test2', 'User2');
Was this page helpful?
0 / 5 - 0 ratings

Related issues

koskimas picture koskimas  路  3Comments

mishitpatel picture mishitpatel  路  3Comments

saurabhghewari picture saurabhghewari  路  3Comments

zettam picture zettam  路  3Comments

aj0strow picture aj0strow  路  3Comments