我可以将实体字段名称映射到 typeorm 中的别名列名称吗? [英] Can I map entity field names to alias column names in typeorm?

查看:126
本文介绍了我可以将实体字段名称映射到 typeorm 中的别名列名称吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 TypeORM 从 Rails 迁移到 NestJs.由于历史原因,Rails 中的表名和列名都是蛇形的——我不想把这个麻烦复制到我们的 NestJs/React 端

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

我可以在 NestJS (typeorm) 中创建名为 firstName 的实体字段,但映射到我的数据库中名为 first_name 的列吗?

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

我的桌子

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

我的用户实体类

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)
}

推荐答案

我终于在文档中找到了我想要的东西.@Column 属性接收许多属性,其中之一是 name,它可以定义与字段关联的列名.

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.

我更新的实体:

@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; 
}

这篇关于我可以将实体字段名称映射到 typeorm 中的别名列名称吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆