Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I map entity field names to alias column names in TypeORM?

Tags:

typeorm

nestjs

I am in the process of migrating from Rails to NestJs with TypeORM. For historical reasons, table names and column names in Rails are snaked_cased - I don't want to copy this nuisance to our NestJs/React side.

Can I create entity fields in NestJS (typeorm) called firstName but are mapped to a column named first_name in my DB?

My table

+-------------+--------------+----------------------------+
|                      system_users                       |
+-------------+--------------+----------------------------+
| id          | int(11)      | PRIMARY KEY AUTO_INCREMENT |
| first_name  | varchar(100) |                            |
| last_name   | varcahr(100) |                            |
+-------------+--------------+----------------------------+

My User Entity Class

import { Entity, Column, PrimaryGeneratedColumn } from 'typeorm';

@Entity({ name: 'system_users' })
export class User {
  @PrimaryGeneratedColumn()
  id: number;

  @Column({ length: 255 })
  first_name: string; // <-- I WANT THIS TO BE firstName (camelCased)

  @Column({ length: 255 })
  last_name: string;  // <-- I WANT THIS TO BE lastName (camelCased)
}
like image 996
Adrian E Avatar asked May 26 '19 06:05

Adrian E


People also ask

How do I change the column name in Typeorm?

name: string - Column name in the database table. By default the column name is generated from the name of the property. You can change it by specifying your own name.


1 Answers

I finally found what I was looking for in the documentation. The @Column attribute receives many properties, one of them is name which can define the column name associated with the field.

My updated entity:

@Entity({ name: 'system_users' })
export class User {
  @PrimaryGeneratedColumn()
  id: number;

  @Column({ length: 255, name: "first_name" })
  firstName: string; 

  @Column({ length: 255, name: "last_name" })
  lastName: string; 
}
like image 135
Adrian E Avatar answered Sep 29 '22 12:09

Adrian E