简体   繁体   中英

How to dynamically get column names from TypeORM?

I have tried

let modelClass = (await import('@models/' + modelName + '.ts'))[modelName];
let keys = Object.keys(modelClass);//no column names included, only custom helper vars i.e. NoteColumnVarcharLength
let keys = Object.keys(new modelClass());//nothing at all in this model

Is there a helper function in the library to automatically get them all?

As proposed in the issue on repository of that library ( link ) can be solved by using

connection.getMetadata("User").columns

The accepted answer looks incomplete, and many questions appeared in my head when I tried to apply the answer. So I write my own to cover the question well.

To get column names, we must first retrieve EntityMetadata . We can retrieve EntityMetadata from Connection , which we can get in any comfortable way.

import { getConnection, getManager } from 'typeorm';

const connection1 = getConnection();
const connection2 = getManager().connection;

Next, we need to retrieve entity metadata.

We can do it via

const metadata = connection.getMetadata(modelClass);

Inside entity medatata you can use several options to find a column. If you need to look for all columns, you need to use columns . If you are going to look only over user-defined columns, you can use ownColumns .

These properties contains arrays with ColumnMetadata .

If you just need a list of user-defined columns, you can just return a mapped values of propertyName .

const columns = metadata.columns.map((column) => column.propertyName);

In my case, I needed to find database column name by a property name.

I used a find() for my case.

const column = metadata.ownColumns.find((column) => column.propertyName === propertyName);

If I need to find several column I would create a map between propertyName and databaseName ;

const columnMap = Object.fromEntries(
  metadata.ownColumns((column) => ([column.propertyName, column. databaseName]))
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM